CODE THE HERO

Home › Learn › World 3: Hash Harbor

FREE

Longest 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

TimeO(n)
SpaceO(n)

How the stars are earned

  1. Correct on every test
  2. At most n² locker visits
  3. 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.

▶ 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