Prefix sums
medium 20 minWrite 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
- 30
- 11
- 42
- 13
- 54
P (prefix sums)
- 00
- ·1
- ·2
- ·3
- ·4
- ·5
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
- 30
- 11
- 42
- 13
- 54
- 95
- 26
- 67
P (prefix sums)
- 00
- ·1
- ·2
- ·3
- ·4
- ·5
- ·6
- ·7
- ·8
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]
criticalWith 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.
Wrongdef range_sum(P, l, r): return P[r] - P[l] # drops a[r]Rightdef range_sum(P, l, r): return P[r + 1] - P[l] # through r, minus before lBuilding P without the leading 0
majorWith 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.
WrongP = 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]RightP = [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}
criticalRuns 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.
Wrongseen = {}for x in a: prefix += x count += seen.get(prefix - k, 0)Rightseen = {0: 1} # the empty prefixfor x in a: prefix += x count += seen.get(prefix - k, 0)Recording the prefix before looking it up
majorWith 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.
Wrongprefix += xseen[prefix] = seen.get(prefix, 0) + 1count += seen.get(prefix - k, 0) # finds itself when k = 0Rightprefix += xcount += seen.get(prefix - k, 0) # earlier prefixes onlyseen[prefix] = seen.get(prefix, 0) + 1Overwriting the first index in contiguous array
majorFor 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.
Wrongif balance in first: best = max(best, i - first[balance])first[balance] = i # overwrites the earliest indexRightif balance in first: best = max(best, i - first[balance])else: first[balance] = i # only the first timeDifference array one cell too short
minorAn 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.
WrongD = [0] * nD[l] += vD[r + 1] -= v # IndexError when r = n - 1RightD = [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.