Home › Learn › World 2: Twin Rivers
FREEThe 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.index | Where each drone is |
Math.max(a, b) | The bigger of two numbers |
submit(value) | Hand in the total water |
What it costs
| Time | O(n) |
| Extra space | O(1) |
How the stars are earned
- Correct on every test
- At most 2n + 2 reads
- 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.
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
- Row to the Pair: Two pointers on sorted data, O(n)
- Palindrome Ferry: Two pointers from both ends, O(n)
- Remove Duplicates: Read pointer and write pointer, O(n)
- The Sliding Net: Sliding window, O(n)
- Stretchy Net: Variable sliding window, O(n)
- Container Dock: Two pointers, greedy O(n)