Home › Learn › World 2: Twin Rivers
FREEStretchy 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:
target | The 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.size | First barrel in the net / how many it covers |
submit(value) | Hand in the smallest size |
What it costs
| Time | O(n) |
| Extra space | O(1) |
How the stars are earned
- Correct on every test
- At most n² reads
- 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.
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)
- Container Dock: Two pointers, greedy O(n)
- The Flood: Trapping rain water, two pointers O(n)