AlgoViz

Prefix sums

medium 20 min

Write the running totals of an array into P once, with P[0] = 0, and the sum of any range a[l..r] becomes one subtraction, P[r + 1] - P[l].

See it run

Pay once to write the running totals into P, then answer any range sum, count or balance question with one subtraction or one lookup.

Operations

Build P with P[0] = 0

One pass: P[i + 1] = P[i] + a[i]. P has n + 1 cells, and P[i] is the sum of the first i elements, a[0..i-1].

Step 1 of 7

Start: P[0] = 0

a

  1. 30
  2. 11
  3. 42
  4. 13
  5. 54

P (prefix sums)

  1. 00
  2. ·1
  3. ·2
  4. ·3
  5. ·4
  6. ·5
len(P) = 5 + 1 = 6

Array [3, 1, 4, 1, 5] has 5 elements, so P gets 6 slots. P[0] = 0 is the sum of no elements: the empty prefix. It is what makes queries that start at index 0 work without a special case.

Step 1: Start: P[0] = 0

def build_prefix(a):    P = [0] * (len(a) + 1)        # P[0] = 0: the sum of no elements    for i in range(len(a)):        P[i + 1] = P[i] + a[i]    # one addition per element    return PP = build_prefix([3, 1, 4, 1, 5])  # [0, 3, 4, 8, 9, 14]
Time
O(n)
Space
O(n)
Additions
exactly n
P[n]
the total

P[i] means the sum of the first i elements. Say it that way and the off-by-one sorts itself out.

In the real world

The same prefix sums doing real jobs. Pick one and step through it.

The original app's eight-element array [3, 1, 4, 1, 5, 9, 2, 6]: eight additions to build P, then sum(1, 4) in one subtraction.

Step 1 of 13

Start: P[0] = 0

a

  1. 30
  2. 11
  3. 42
  4. 13
  5. 54
  6. 95
  7. 26
  8. 67

P (prefix sums)

  1. 00
  2. ·1
  3. ·2
  4. ·3
  5. ·4
  6. ·5
  7. ·6
  8. ·7
  9. ·8
len(P) = 8 + 1 = 9

Array [3, 1, 4, 1, 5, 9, 2, 6] has 8 elements, so P gets 9 slots. P[0] = 0 is the sum of no elements: the empty prefix. It is what makes queries that start at index 0 work without a special case.

Step 1: Start: P[0] = 0

def build_prefix(a):    P = [0] * (len(a) + 1)        # P[0] = 0: the sum of no elements    for i in range(len(a)):        P[i + 1] = P[i] + a[i]    # one addition per element    return PP = build_prefix([3, 1, 4, 1, 5])  # [0, 3, 4, 8, 9, 14]def range_sum(P, l, r):    """Sum of a[l..r], both ends inclusive."""    return P[r + 1] - P[l]

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Reading P[r] instead of P[r + 1]

    critical

    With the n + 1 convention Pr stops before index r, so the last element of the range is lost. On [3, 1, 4, 1, 5], sum(1, 3) comes out as 8 - 3 = 5 instead of 6.

    Wrong
    def range_sum(P, l, r):    return P[r] - P[l]          # drops a[r]
    Right
    def range_sum(P, l, r):    return P[r + 1] - P[l]      # through r, minus before l
  • Building P without the leading 0

    major

    With an inclusive P of length n, a query starting at 0 reads P[l - 1] = P[-1], which Python quietly turns into the LAST element. sum(0, 2) on [3, 1, 4, 1, 5] returns 8 - 14 = -6.

    Wrong
    P = list(itertools.accumulate(a))   # [3, 4, 8, 9, 14]def range_sum(l, r):    return P[r] - P[l - 1]              # l = 0 reads P[-1]
    Right
    P = [0] + list(itertools.accumulate(a))   # [0, 3, 4, 8, 9, 14]def range_sum(l, r):    return P[r + 1] - P[l]
  • Forgetting to seed the map with {0: 1}

    critical

    Runs that start at index 0 need the empty prefix P[0] = 0 to be in the map. Without it, [3] with k = 3 returns 0 and [1, 2, 1, -2, 3] returns 2 instead of 3.

    Wrong
    seen = {}for x in a:    prefix += x    count += seen.get(prefix - k, 0)
    Right
    seen = {0: 1}                # the empty prefixfor x in a:    prefix += x    count += seen.get(prefix - k, 0)
  • Recording the prefix before looking it up

    major

    With k = 0 the current prefix matches itself, counting an empty run at every index. [1, -1] with k = 0 should give 1 but returns 3.

    Wrong
    prefix += xseen[prefix] = seen.get(prefix, 0) + 1count += seen.get(prefix - k, 0)        # finds itself when k = 0
    Right
    prefix += xcount += seen.get(prefix - k, 0)        # earlier prefixes onlyseen[prefix] = seen.get(prefix, 0) + 1
  • Overwriting the first index in contiguous array

    major

    For the LONGEST run you need the EARLIEST index of each balance. Updating it every time shrinks the runs: [0, 1, 0, 0, 1, 1, 0] returns 4 instead of 6.

    Wrong
    if balance in first:    best = max(best, i - first[balance])first[balance] = i                   # overwrites the earliest index
    Right
    if balance in first:    best = max(best, i - first[balance])else:    first[balance] = i               # only the first time
  • Difference array one cell too short

    minor

    An update that runs to the last index writes D[r + 1] = D[n]. With only n cells that is an IndexError. Give D n + 1 cells and simply never read the last one.

    Wrong
    D = [0] * nD[l] += vD[r + 1] -= v       # IndexError when r = n - 1
    Right
    D = [0] * (n + 1)D[l] += vD[r + 1] -= v       # D[n] just absorbs it

Interview tips

  • How to explain it

    • P[i] is the sum of the first i elements, so P has n + 1 cells and P[0] = 0.
    • sum(l, r) = P[r + 1] - P[l]: the shared part before l cancels.
    • O(n) to build, O(1) per query, so q queries cost O(n + q).
    • For counting runs, store prefix values in a map as you go.
  • Spot it in problems

    • Many range sum queries on an array that does not change.
    • Count or find subarrays with sum k, especially with negatives.
    • Equal numbers of two things in a run: map them to +1 and -1.
    • Many range updates, read once at the end: difference array.
  • Memory tricks

    • Running total: each P cell answers 'how much so far?'
    • Through r minus before l.
    • Seed, look up, record: {0: 1}, prefix - k, then prefix.
    • 2D: big, minus top, minus left, plus the corner.
  • Watch out

    • P[r + 1], not P[r], with the n + 1 convention.
    • Updates between queries break plain prefix sums: use a Fenwick or segment tree.
    • Longest run: first index. Number of runs: counts.