Fill in

Prefix Sums

The Guild ledger records lantern oil used each day. Visitors keep asking: "How much oil from day 3 to day 9?" Summing the slice each time is O(n) per question. With prefix sums every question takes O(1) after one O(n) setup.

prefix[i] = total of the first i values (so prefix[0] is 0):

values: [3, 1, 4, 1, 5]
prefix: [0, 3, 4, 8, 9, 14]

The total of values[start:end] is then just prefix[end] - prefix[start]. For values[1:4] that is 9 - 3 = 6 (that's 1 + 4 + 1). ✔

Pip tip: itertools.accumulate(values, initial=0) builds the same prefix list in one line.

Assignment

Replace each ___:

  1. build_prefix(values) returns the prefix list (one longer than values).
  2. range_total(prefix, start, end) returns the sum of values[start:end] (end excluded) using only prefix.