CODE THE HERO

Home › Learn › World 3: Hash Harbor

FREE

Two 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:

targetThe 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

TimeO(n)
SpaceO(n)

How the stars are earned

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

▶ 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