CODE THE HERO

Home › Learn › World 3: Hash Harbor

FREE

Anagram 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

TimeO(n)
SpaceO(alphabet)

How the stars are earned

  1. Correct verdict on every test
  2. At most 2 reads per letter
  3. 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.

▶ Play this level free

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