Home › Learn › World 3: Hash Harbor
FREEFrequency Board
Counting with a hash map, O(n)
Level 3.3 of Code the Hero, in Hash Harbor: hash maps: find anything in one visit.
The idea
A hash map from item to count builds a frequency table in one pass — the basis of anagram, majority and top-k problems.
The mission
The harbor board must show how many of each cargo arrived today. Use each cargo name as a key. Its locker holds the count so far. New cargo? Start at 1. Seen before? Add 1 to what's already there.
Goal: When your code ends, each cargo's locker must hold how many times it arrived.
The commands you get
You write real Python, Java or JavaScript. These are the moves the hero understands in this level:
parcels.length / parcels.get(i) | Read cargo i's name |
lockers.get(key) | Count so far, or undefined if none |
lockers.put(key, value) | Store the new count |
What it costs
| Time | O(n) |
| Space | O(distinct items) |
How the stars are earned
- Correct board on every test
- At most 2n reads
- At most n reads
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)
- Two Sum Harbor: Hash map complement lookup, O(n)
- Anagram Crates: Letter counts in a hash map, O(n)
- Longest Chain: Hash set sequence starts, O(n)
- Smuggler Twins: Prefix sums + hash map, O(n)