Same Letter Tiles

Easyhash mapAlso known as Valid Anagram

You are playing a word game with letter tiles. You lay down listen. Your friend scoops up your six tiles, shuffles them, and lays down silent. Legal move: same tiles, new order.

Next round she tries to turn your teeth into teethe. That needs a sixth tile she does not have. You want a quick way to check any claimed rearrangement.

Your task

Write sameTiles(word, rearranged). Return true if rearranged uses exactly the same letters as word, each letter the same number of times, in any order. Otherwise return false.

Both strings contain only lowercase letters a to z. Two empty strings count as the same tiles.

sameTiles(word: string, rearranged: string) → bool

Examples

Example 1
Input
word = "listen"
rearranged = "silent"
Output
true
Why

Both have one each of e, i, l, n, s, t. The order is different, the tiles are the same.

Example 2
Input
word = "teeth"
rearranged = "teethe"
Output
false
Why

The lengths differ, 5 against 6, so at least one tile is missing. No need to look further.

Example 3
Input
word = "brag"
rearranged = "garb"
Output
true
Why

b, r, a, g in both. Shuffled, but nothing added and nothing left over.

Constraints

  • 0 ≤ word.length, rearranged.length ≤ 50,000
  • Only lowercase English letters.
Start with brute force

For each letter of word, search rearranged for a matching unused tile and cross it off. If you ever fail to find one, the answer is no.

Each search scans the second word, so this is O(n²). With 50,000 letters that is over a billion steps. Sorting both words and comparing them works in O(n log n), which is fine, but counting is simpler and faster.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code