ENع
←Prefix sums
Lesson 52 · Strings and problem-solving patterns

Prefix sums

12 min8 steps5 questionsAdvanced
About this lesson

Many problems ask the same kind of question again and again: what is the total of this stretch of an array? Adding the stretch up every time is slow. A prefix sum adds the whole array up once, into a second array of running totals, and then answers any range sum with one subtraction. Watch it built for a = [3, 1, 4, 1, 5, 9], one slot at a time, and then used to answer a[2:5] = 10. The Software lessons on strings and on searching cover lists, indexes and slices, which this lesson uses throughout.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 52 · Interactive
01 / 08

Many range sums

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.

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
Loading figure…
or ← →
Read the lesson step by step
  1. Many range sums

    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.

    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
  2. The plain way: add them up

    The plain way walks the range and adds each item: 4, then 5, then 10. That is hi − lo additions per query. With n items and q queries, it can cost about n × q additions.

    def range_sum_slow(a, lo, hi):
        return sum(a[lo:hi])
    
    a[2:5]: +4 → 4   +1 → 5   +5 → 10
    3 additions for this query
    worst case: n additions per query, n·q for q queries
  3. Add up once, up front

    Better: add up once, up front. Build a second array p, where p[i] is the sum of the first i items of a. It starts with p[0] = 0, the sum of no items at all.

    p[i] = a[0] + a[1] + ... + a[i - 1]   (= sum(a[:i]))
    p[0] = 0         the empty sum
    p has len(a) + 1 = 7 slots
    
    line 2:  p = [0]
  4. Each slot reuses the last

    Each new slot reuses the one before it: p[i + 1] = p[i] + a[i]. So p[1] = 0 + 3 = 3 and p[2] = 3 + 1 = 4. One addition per slot, never a recount.

    line 4:  p.append(p[-1] + x)
    p[-1] is the last slot so far, x is the next item
    
    p[1] = p[0] + a[0] = 0 + 3 = 3
    p[2] = p[1] + a[1] = 3 + 1 = 4
  5. Build the whole prefix array

    Carry on to the end: p = [0, 3, 4, 8, 9, 14, 23]. That took 6 additions for 6 items, so building p costs O(n) time. p has n + 1 slots, and the last one is the total.

    p[3] = p[2] + a[2] = 4 + 4 = 8
    p[4] = p[3] + a[3] = 8 + 1 = 9
    p[5] = p[4] + a[4] = 9 + 5 = 14
    p[6] = p[5] + a[5] = 14 + 9 = 23
    
    prefix(a) = [0, 3, 4, 8, 9, 14, 23]
    p[6] = 23 = sum(a)
    n additions: O(n) time, n + 1 slots of memory
  6. One subtraction per query

    Now a range sum is one subtraction: sum(a[lo:hi]) = p[hi] − p[lo]. p[5] = 3+1+4+1+5 and p[2] = 3+1. The shared 3+1 cancels, leaving 4+1+5: 14 − 4 = 10.

    line 8:  return p[hi] - p[lo]
    
    p[5] = 3 + 1 + 4 + 1 + 5 = 14
    p[2] = 3 + 1             = 4
    p[5] - p[2] = 4 + 1 + 5 = 14 - 4 = 10
    two lookups and one subtraction: O(1)
  7. Why p starts with 0

    The same p answers every range. The whole array: p[6] − p[0] = 23 − 0 = 23. This is why p starts with a 0: a range that starts at index 0 still needs a p[lo].

    range_sum(p, 0, 6) = p[6] - p[0] = 23 - 0 = 23
    range_sum(p, 3, 4) = p[4] - p[3] = 9 - 8 = 1  (just a[3])
    range_sum(p, 2, 2) = p[2] - p[2] = 0       (empty range)
    
    without p[0] = 0, ranges from index 0 would need a special case
  8. The trade: memory for time

    The trade: O(n) time and O(n) extra memory once, then O(1) per query, however long the range. q queries cost about n + q steps instead of n × q. If a changes, p must be rebuilt.

                     build    one query   q queries
      plain loop     -        O(n)        O(n·q)
      prefix sums    O(n)     O(1)        O(n + q)
    
    extra memory: n + 1 numbers
    a changes -> rebuild p (O(n))

Quiz Unlocks after the last step.