Home › Learn › World 3: Hash Harbor
FREEAnagram Crates
Letter counts in a hash map, O(n)
Level 3.5 of Code the Hero, in Hash Harbor: hash maps: find anything in one visit.
The idea
Two strings are anagrams exactly when their letter-frequency tables match. Counting beats sorting: O(n) instead of O(n log n).
The mission
Two crates carry letter tiles. Do they hold exactly the same letters, just shuffled? Count every letter of word A in the lockers. Then use them up with word B. If B needs a letter that's run out, they're not anagrams.
Goal: submit(true) if wordA and wordB use exactly the same letters, otherwise submit(false).
The commands you get
You write real Python, Java or JavaScript. These are the moves the hero understands in this level:
wordA.length / wordA.get(i) | Letters of the first word |
wordB.length / wordB.get(i) | Letters of the second word |
lockers.get(key) / lockers.put(key, value) | Letter counts |
submit(bool) | Hand in your verdict |
What it costs
| Time | O(n) |
| Space | O(alphabet) |
How the stars are earned
- Correct verdict on every test
- At most 2 reads per letter
- Each letter read once
Your code is also checked on hidden inputs, so it has to work for any case, not only the one on screen.
No sign-up. Levels open in order, so if this one is still locked you start at the first level that isn't.
More in Hash Harbor
- Locker Room: Hash map put and get, O(1) each
- Duplicate Parcel: Hash set membership, O(n)
- Frequency Board: Counting with a hash map, O(n)
- Two Sum Harbor: Hash map complement lookup, O(n)
- Longest Chain: Hash set sequence starts, O(n)
- Smuggler Twins: Prefix sums + hash map, O(n)