CODE THE HERO

Home › Learn › World 2: Twin Rivers

FREE

Stretchy Net

Variable sliding window, O(n)

Level 2.5 of Code the Hero, in Twin Rivers: two pointers and sliding windows.

The idea

Grow the window until it satisfies the goal, then shrink it while it still does. Both edges only move right, so the whole scan is O(n).

The mission

This net stretches! I need the smallest net whose barrels weigh at least the target together. Grow the net to the right until it's heavy enough. Then shrink it from the left while it still is. Every barrel enters the net once and leaves once. No barrel is read more than twice.

Goal: submit the fewest neighbouring barrels with total at least target, or 0 if no net is heavy enough.

The commands you get

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

targetThe weight the net must reach
crates.get(i)Read barrel i
net.grow()Stretch the net over the next barrel on the right
net.shrink()Let go of the leftmost barrel in the net
net.start / net.sizeFirst barrel in the net / how many it covers
submit(value)Hand in the smallest size

What it costs

TimeO(n)
Extra spaceO(1)

How the stars are earned

  1. Correct on every test
  2. At most n² reads
  3. At most 2n reads

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 Twin Rivers