Home › Learn › World 2: Twin Rivers
FREEThe Sliding Net
Sliding window, O(n)
Level 2.4 of Code the Hero, in Twin Rivers: two pointers and sliding windows.
The idea
A fixed-size window keeps a running total; each slide costs one add and one subtract instead of k additions.
The mission
The fishing net covers k barrels at once. Which k neighbours are heaviest together? Lazy way: re-add every barrel in the net at each position. Slow! Clever way: when the net slides, add the barrel that enters and subtract the one that leaves.
Goal: Find the biggest total weight of any net.size neighbouring barrels and submit(best).
The commands you get
You write real Python, Java or JavaScript. These are the moves the hero understands in this level:
crates.get(i) | Hero reads barrel i |
crates.length | Number of barrels |
net.size | How many barrels the net covers (k) |
net.slide() | Slide the net one barrel right |
net.start | First barrel under the net |
submit(value) | Hand in the best total |
What it costs
| Time | O(n) |
| Extra space | O(1) |
How the stars are earned
- Correct on every test
- At most k × (n − k + 1) reads
- At most k + 2 × (n − k) reads: true sliding
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)
- Stretchy Net: Variable sliding window, O(n)
- Container Dock: Two pointers, greedy O(n)
- The Flood: Trapping rain water, two pointers O(n)