Home › Learn › World 2: Twin Rivers
FREEContainer Dock
Two pointers, greedy O(n)
Level 2.6 of Code the Hero, in Twin Rivers: two pointers and sliding windows.
The idea
The shorter post limits the water, so any dock using it with a closer partner is worse. Discard it and move inward.
The mission
Two posts and the river between them make a dock. Water fills up to the shorter post. Water = shorter post × distance. Start with the widest dock: the two ends. Moving the taller post can never help. Always move the drone on the shorter post.
Goal: submit the most water any two posts can hold.
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 of the post under each drone |
pip.right() / pix.left() | Move a drone inward |
pip.index / pix.index | Where each drone is |
Math.min / Math.max | Smaller / bigger of two numbers |
submit(value) | Hand in the most water |
What it costs
| Time | O(n) |
| Extra space | O(1) |
How the stars are earned
- Correct on every test
- At most 2n reads
- At most n + 1 reads: read each post once
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)
- The Flood: Trapping rain water, two pointers O(n)