Home › Learn › World 3: Hash Harbor
FREELongest Chain
Hash set sequence starts, O(n)
Level 3.6 of Code the Hero, in Hash Harbor: hash maps: find anything in one visit.
The idea
Only numbers with no predecessor start a chain, so each number is stepped over once: O(n) instead of sorting's O(n log n).
The mission
Parcel numbers are jumbled. What's the longest run of consecutive numbers, like 4, 5, 6, 7? Put every number in the lockers first. A chain can only START at x if x - 1 isn't there. From each start, count upward while the next number is in a locker.
Goal: submit the length of the longest run of consecutive numbers (in any order in the row).
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 parcel i |
lockers.put(key, value) | Store a number |
lockers.has(key) | Is this number stored? (1 visit) |
new Set() | Your own set, to skip starts you've already counted |
submit(value) | Hand in the longest length |
What it costs
| Time | O(n) |
| Space | O(n) |
How the stars are earned
- Correct on every test
- At most n² locker visits
- At most 2n locker visits
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)
- Anagram Crates: Letter counts in a hash map, O(n)
- Smuggler Twins: Prefix sums + hash map, O(n)