1def prefix(a):2 p = [0]3 for x in a:4 p.append(p[-1] + x)5 return p67def range_sum(p, lo, hi):8 return p[hi] - p[lo]a[0]3a[1]1a[2]4a[3]1a[4]5a[5]9a[2:5]p[0]p[1]p[2]p[3]p[4]p[5]p[6]answer
Back row: the array a. Front row: the prefix array p, p[i] = sum of the first i itemsTape: the range a[2:5] (index 2 up to, not including, 5)Hopping tokens: values read from a cell and combined in anotherThe array a = [3, 1, 4, 1, 5, 9] sits behind the prefix array p, offset half a cell so a[i] lies between p[i] and p[i + 1]. Building p, the tokens from p[i] and a[i] meet in p[i + 1]: one addition per slot. A range sum is then p[hi] − p[lo]: for a[2:5], 14 − 4 = 10.

The question

  1. An array a holds 6 numbers. We want range sums: the total of a[lo:hi], the items from index lo up to, but not including, hi. Example: a[2:5] covers 4, 1, 5.

Build the prefix array

One subtraction per query

What happens

;; step 1/8 · the-question
a = [3, 1, 4, 1, 5, 9]
index:  0  1  2  3  4  5

range sum a[lo:hi] = a[lo] + ... + a[hi - 1]
a[2:5] = 4 + 1 + 5 = 10
Python slices are half-open: lo is in, hi is out

a[lo:hi] follows Python slicing: it holds the items with index k where lo ≤ k < hi, so a[2:5] is a[2], a[3] and a[4]. That half-open rule is what makes p[hi] − p[lo] come out exactly right, with no ± 1. Python can build the same array for you: list(itertools.accumulate(a, initial=0)) returns [0, 3, 4, 8, 9, 14, 23]. The initial argument was added in Python 3.8.