Home › Learn › World 3: Hash Harbor
FREETwo Sum Harbor
Hash map complement lookup, O(n)
Level 3.4 of Code the Hero, in Hash Harbor: hash maps: find anything in one visit.
The idea
Instead of trying every pair, ask a hash map whether the needed complement has already appeared.
The mission
Two parcels together must weigh the target. This time the row isn't sorted! For each parcel, the partner you need is target minus its weight. Keep every weight you've passed in a locker, with its position. Is the partner already there?
Goal: Find two different parcels whose weights add up to target and submit(i, j).
The commands you get
You write real Python, Java or JavaScript. These are the moves the hero understands in this level:
target | The total you need |
parcels.length / parcels.get(i) | Read parcel i |
lockers.has(key) / lockers.get(key) | Look up a weight |
lockers.put(key, value) | Remember a weight and its position |
submit(i, j) | Hand in the two positions |
What it costs
| Time | O(n) |
| Space | O(n) |
How the stars are earned
- Correct pair on every test
- At most n² reads
- At most n reads: one pass
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)
- 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)