CODE THE HERO

Home › Learn › World 2: Twin Rivers

FREE

The Flood

Trapping rain water, two pointers O(n)

World 2 boss of Code the Hero, in Twin Rivers: two pointers and sliding windows.

The idea

Water at a spot depends on the smaller of the two tallest walls around it. Moving from the lower side guarantees that side's max is the limiting one.

The mission

The Flood pours rain over the barrels. Water pools in every dip between taller barrels. Water above a barrel = the lower of the tallest barrel to its left and to its right, minus its height. Work from the lower side: its tallest-so-far already decides the water there.

Goal: submit the total units of water trapped between the barrels.

Boss: The Flood. Hidden tests include flat rows and single peaks. Read each barrel about once for three stars.

The commands you get

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

pip.read() / pix.read()Height under each drone
pip.right() / pix.left()Move a drone inward
pip.index / pix.indexWhere each drone is
Math.max(a, b)The bigger of two numbers
submit(value)Hand in the total water

What it costs

TimeO(n)
Extra spaceO(1)

How the stars are earned

  1. Correct on every test
  2. At most 2n + 2 reads
  3. At most n + 1 reads, O(1) extra space

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