Home › Learn › World 2: Twin Rivers
FREERow to the Pair
Two pointers on sorted data, O(n)
Level 2.1 of Code the Hero, in Twin Rivers: two pointers and sliding windows.
The idea
In sorted data, the sum of the two ends tells you which end is useless: a too-small sum can't use the left barrel with anything, so drop it.
The mission
The barrels float in order, lightest to heaviest. I need two that add up to the target exactly. Pip starts at the left end and Pix at the right. Each can read the barrel under it. Sum too small? Move Pip right. Too big? Move Pix left. They never need to go back.
Goal: Find two barrels whose weights add up to target, then submit(pip.index, pix.index).
The commands you get
You write real Python, Java or JavaScript. These are the moves the hero understands in this level:
target | The sum you need |
pip.read() / pix.read() | Weight of the barrel under that drone |
pip.right() | Move Pip one barrel right |
pix.left() | Move Pix one barrel left |
pip.index / pix.index | Where each drone is |
submit(i, j) | Hand in the two positions |
What it costs
| Time | O(n) |
| Extra space | O(1) |
How the stars are earned
- Correct pair on every test
- Solved
- At most one read per drone per step
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
- 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)
- The Flood: Trapping rain water, two pointers O(n)