Home › Learn › World 1: Array Plains
FREEIrrigation Channels
Prefix sums: O(n) build, O(1) query
Level 1.4 of Code the Hero, in Array Plains: scan, swap and sort a row of crates.
The idea
Pay O(n) once to build running totals; afterwards any range total is a subtraction of two cells.
The mission
My fields need water totals for stretches of crates. Adding them up every time takes forever! Fill the channel with running totals: cell i holds crate 0 + crate 1 + ... + crate i. Then any stretch from l to r is just channel[r] minus channel[l - 1]. Two reads!
Goal: Fill channel with running totals, then submit the total of crates l to r.
The commands you get
You write real Python, Java or JavaScript. These are the moves the hero understands in this level:
crates.length | How many crates |
crates.get(i) | Hero lifts crate i |
channel.set(i, v) | Fill channel cell i with water level v |
channel.get(i) | Read channel cell i |
l, r | The stretch of crates to total (both included) |
submit(value) | Hand in the total |
What it costs
| Build | O(n) |
| Each query | O(1) |
| Extra space | O(n) |
How the stars are earned
- Channel and total correct on every test
- At most 2n crate lifts
- At most n crate lifts
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 Array Plains
- The Heaviest Crate: Linear scan, O(n)
- Reverse the Row: Two pointers, n/2 swaps
- Count the Apples: Counting in one pass, O(n)
- Rotate the Row: Rotation by three reversals, O(n)
- Bubble Sort Machine: Sorting by adjacent swaps, O(n²)
- Storm Harvester: Kadane's algorithm, O(n)