CODE THE HERO

Home › Learn › World 1: Array Plains

FREE

Irrigation 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.lengthHow 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, rThe stretch of crates to total (both included)
submit(value)Hand in the total

What it costs

BuildO(n)
Each queryO(1)
Extra spaceO(n)

How the stars are earned

  1. Channel and total correct on every test
  2. At most 2n crate lifts
  3. 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.

▶ Play this level free

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