Same Letter Tiles

Easyhash mapAlso known as Valid Anagram

In a word game, you lay down listen. Your friend shuffles your six tiles and lays down silent: same tiles, new order, a legal move.

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

Your task

Write sameTiles(word, rearranged). Return true if rearranged uses exactly the same letters as word, each 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 words have one each of e, i, l, n, s and t, so they use the same tiles in a different order.

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

The lengths differ (5 against 6), so the word cannot be a rearrangement and there is no need to compare letters.

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

Both words contain exactly the letters b, r, a and g, so the tiles were shuffled with none added and none left over.

Constraints

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

For each letter of word, find a matching unused tile in rearranged and cross it off. If a letter has no matching tile, the answer is false.

Each search scans the second word: O(n²), over a billion steps for 50,000 letters. Sorting both words and comparing is 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