CODE THE HERO

Home › Learn › World 3: Hash Harbor

FREE

Smuggler Twins

Prefix sums + hash map, O(n)

World 3 boss of Code the Hero, in Hash Harbor: hash maps: find anything in one visit.

The idea

sum(i..j) = prefix[j] - prefix[i-1]. Counting earlier prefixes equal to prefix - k in a hash map finds every run in one pass, even with negatives.

The mission

The Smuggler Twins hid loot in runs of neighbouring parcels adding up to exactly k. Keep a running total. A run ending here adds to k when an earlier running total equals total - k. Store how many times each running total has appeared. Start with total 0 seen once.

Goal: submit how many runs of neighbouring parcels add up to exactly k.

Boss: Smuggler Twins. Parcels can be negative. Hidden tests include zeros and repeated totals.

The commands you get

You write real Python, Java or JavaScript. These are the moves the hero understands in this level:

kThe total each run must reach
parcels.length / parcels.get(i)Read parcel i (can be negative)
lockers.get(key) / lockers.put(key, value)Counts of running totals
submit(value)Hand in the number of runs

What it costs

TimeO(n)
SpaceO(n)

How the stars are earned

  1. Correct 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