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].
Video lesson · Chapter 1 of 9
The returns counter
Prefix sums in 75 seconds
1:27Reel
How it works
Step through the idea, or press Play.
Build P once. P[0] = 0 and P[i + 1] = P[i] + a[i]: n additions, n + 1 cells
Understand it
Recap
Running totals answer range questions
Arrays: O(1) by index
Reading
a[i]is instant, but adding upa[l..r]with a loop costs steps, every time you ask. See static arrays.Hash maps: O(1) lookup
A dict answers 'have I seen this value, and how often?' in on average. Half of this topic leans on it. See hash usage.
The trade
Spend time and space once to store running totals. Every range sum after that is .
Take a = [3, 1, 4, 1, 5]. Its running totals are 3, 4, 8, 9, 14. Put a 0 in front for 'nothing added yet' and you have the prefix array P = [0, 3, 4, 8, 9, 14]. Now the sum of a[1..3], that is , is P[4] - P[1] = 9 - 3 = 6: one subtraction instead of a loop.
Step 1
Build P with P[0] = 0
Definition and recurrence
Building the prefix array
a = [3, 1, 4, 1, 5]
| Step | Computation | P so far |
|---|---|---|
| 0 | P[0] = 0 | [0] |
| 1 | P[1] = P[0] + a[0] = 0 + 3 | [0, 3] |
| 2 | P[2] = P[1] + a[1] = 3 + 1 | [0, 3, 4] |
| 3 | P[3] = P[2] + a[2] = 4 + 4 | [0, 3, 4, 8] |
| 4 | P[4] = P[3] + a[3] = 8 + 1 | [0, 3, 4, 8, 9] |
| 5 | P[5] = P[4] + a[4] = 9 + 5 | [0, 3, 4, 8, 9, 14] |
a has indices 0 to 4; P has indices 0 to 5. Each P[i] sits on the fence between a[i - 1] and a[i].from itertools import accumulatedef build_prefix(a): P = [0] * (len(a) + 1) for i in range(len(a)): P[i + 1] = P[i] + a[i] return Pa = [3, 1, 4, 1, 5]print(build_prefix(a)) # [0, 3, 4, 8, 9, 14]print([0] + list(accumulate(a))) # the sameitertools.accumulate does the running total; the leading 0 is up to you.Step 2
Any range sum in O(1)
Why one subtraction is enough
Queries on P = [0, 3, 4, 8, 9, 14]
| Query | Elements | Formula | Answer |
|---|---|---|---|
sum(1, 3) | 1 + 4 + 1 | P[4] - P[1] = 9 - 3 | 6 |
sum(0, 4) | the whole array | P[5] - P[0] = 14 - 0 | 14 |
sum(2, 2) | just a[2] | P[3] - P[2] = 8 - 4 | 4 |
sum(3, 4) | 1 + 5 | P[5] - P[3] = 14 - 8 | 6 |
Convention
The off-by-one, settled once
Length n + 1, P[0] = 0 (use this)
P[i]= sum ofa[0..i-1], the first elements.sum(l, r) = P[r + 1] - P[l], no branches.- Matches half-open ranges: is
P[r + 1] - P[l]. - The same shape as the
{0: 1}seed and the 2D zero border.
Length n, inclusive (avoid)
Q[i]= sum ofa[0..i], includinga[i].sum(l, r) = Q[r] - Q[l - 1], which needs anif l == 0branch.- In Python, forgetting the branch reads
Q[-1], the total, with no error. - Each formula needs its own fiddly edge case.
Nothing is lost by switching to P: every original value comes back as , a range of length one. That identity is also the bridge to difference arrays at the end of this page.
Cost
When prefix sums pay off
| Approach | Build | Per query | q queries | Extra space |
|---|---|---|---|---|
| Loop over the range | none | worst | ||
| Prefix sums | $O(1)$ | $O(n + q)$ | ||
| Fenwick or segment tree |
Paying once versus paying every time
Which tool for range sums?
Pattern 1
Subarray sum equals k: prefix plus a map
A run with sum k is a pair of prefixes
One pass with a map of prefix counts
def subarray_sum(a, k): seen = {0: 1} # the empty prefix P[0] = 0 prefix = count = 0 for x in a: prefix += x count += seen.get(prefix - k, 0) seen[prefix] = seen.get(prefix, 0) + 1 return countprint(subarray_sum([1, 2, 1, -2, 3], 3)) # 3print(subarray_sum([1, 1, 1], 2)) # 2print(subarray_sum([1, -1, 0], 0)) # 3: [1, -1], [0], [1, -1, 0][1, 2, 1, -2, 3] with it finds [1, 2], [2, 1] and [3].Pattern 1, deeper
Three questions, three maps
| Question | Map stores | Seed | Update rule |
|---|---|---|---|
| How many runs sum to k? | prefix value → count | {0: 1} | always add 1 after the lookup |
| Longest run with sum k? | prefix value → first index | {0: -1} | set only if not present |
| Shortest run with sum k? | prefix value → last index | {0: -1} | overwrite every time |
| How many runs with sum divisible by k? | prefix % k → count | {0: 1} | always add 1 after the lookup |
prefix - k for exact sums and the remainder itself for divisibility: equal remainders differ by a multiple of k.Divisible by k means equal remainders
def longest_sum_k(a, k): first = {0: -1} prefix = best = 0 for i, x in enumerate(a): prefix += x if prefix - k in first: best = max(best, i - first[prefix - k]) first.setdefault(prefix, i) # keep the earliest index return bestdef count_divisible(a, k): seen = {0: 1} prefix = count = 0 for x in a: prefix += x r = prefix % k # Python: always 0..k-1 count += seen.get(r, 0) seen[r] = seen.get(r, 0) + 1 return countprint(longest_sum_k([1, -1, 5, -2, 3], 3)) # 4: [1, -1, 5, -2]print(count_divisible([4, 5, 0, -2, -3, 1], 5)) # 7Pattern 2
Contiguous array: turn 0/1 into a balance
Find the longest run of a binary array with as many 0s as 1s. Counting both is awkward, so count each 1 as and each 0 as . A run is balanced exactly when its sum is 0, which is subarray sum equals with . And since we want the longest, the map stores the first index of each balance.
Balanced run, equal balances
i - first[balance] in the code.Contiguous array, one index at a time
[0, 1, 0, 0, 1, 1, 0] the answer is 6, indices 0 to 5.def find_max_length(bits): first = {0: -1} balance = best = 0 for i, b in enumerate(bits): balance += 1 if b == 1 else -1 if balance in first: best = max(best, i - first[balance]) else: first[balance] = i return bestprint(find_max_length([0, 1, 0, 0, 1, 1, 0])) # 6print(find_max_length([0, 1])) # 2print(find_max_length([0, 0, 0])) # 0Pattern 3
Product of array except self
Prefix times suffix
a = [1, 2, 3, 4]
| i | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| left product (before i) | 1 | 1 | 2 | 6 |
| right product (after i) | 24 | 12 | 4 | 1 |
| out = left × right | 24 | 12 | 8 | 6 |
a[i] itself.def product_except_self(a): n = len(a) out = [1] * n left = 1 for i in range(n): out[i] = left left *= a[i] right = 1 for i in range(n - 1, -1, -1): out[i] *= right right *= a[i] return outprint(product_except_self([1, 2, 3, 4])) # [24, 12, 8, 6]print(product_except_self([2, 0, 3, 4])) # [0, 24, 0, 0]out; the right product is one variable, so extra space is besides the output.2D
2D prefix sums and inclusion-exclusion
Build: add above, add left, subtract the overlap
Query: any rectangle in four reads
M = [[3, 0, 1, 4], [5, 6, 3, 2], [1, 2, 0, 1]], rows 1 to 2 and columns 1 to 2 give , which is .Inclusion-exclusion for one rectangle
def build_2d(M): R, C = len(M), len(M[0]) S = [[0] * (C + 1) for _ in range(R + 1)] for i in range(R): for j in range(C): S[i + 1][j + 1] = M[i][j] + S[i][j + 1] + S[i + 1][j] - S[i][j] return Sdef region_sum(S, r1, c1, r2, c2): return S[r2 + 1][c2 + 1] - S[r1][c2 + 1] - S[r2 + 1][c1] + S[r1][c1]M = [[3, 0, 1, 4], [5, 6, 3, 2], [1, 2, 0, 1]]S = build_2d(M)print(region_sum(S, 1, 1, 2, 2)) # 11print(region_sum(S, 0, 0, 2, 3)) # 28, the whole matrixInverse
Difference arrays: O(1) range updates
Difference and prefix sum undo each other
D[l] += v, D[r + 1] -= v.- 1D = [0] * (n + 1)one spare slot for r + 1 = n
- 2Each updateD[l] += v, D[r + 1] -= v
- 3Prefix sum of Drun += D[i] rebuilds a
- 4Read the resultO(n + q) in total
Prefix sums make range reads cheap; difference arrays make range writes cheap.
def apply_updates(n, updates): D = [0] * (n + 1) for l, r, v in updates: D[l] += v D[r + 1] -= v out, run = [], 0 for i in range(n): run += D[i] out.append(run) return outprint(apply_updates(6, [(1, 3, 2), (2, 5, 3), (0, 1, -1)])) # [-1, 1, 5, 5, 3, 3]print(apply_updates(6, [(0, 2, 3), (1, 4, 2), (3, 5, 4)])) # [3, 5, 5, 6, 6, 4]Wrap-up
Where it fits, and what to remember
Kadane's algorithm
The best run ending at is . Tracking the smallest prefix so far gives maximum subarray in one pass, which is Kadane in disguise.
Sliding window
With non-negative numbers and a 'longest or shortest with sum at most k' question, a variable window uses space. With negatives or exact counts, use the prefix map.
Segment tree
When values change between queries, a segment tree answers range sums and updates in each.
Hash usage
Counting, first-seen indices and remainders are the dict patterns from hash usage, applied to prefix values.
Key points
P[i]is the sum of the first elements;Phas cells andP[0] = 0.sum(l, r) = P[r + 1] - P[l]: to build, per query, for queries.- Subarray sum equals : count earlier prefixes equal to
prefix - k, seeded with{0: 1}, look up before recording. - Longest run: store the first index (seed
{0: -1}). Divisible by : bucket byprefix % k. - Contiguous array: 0 as , 1 as , longest run between equal balances.
- Product except self: exclusive prefix product times exclusive suffix product, no division.
- 2D: build with plus above, plus left, minus corner; query with big minus top minus left plus corner.
- Difference arrays invert prefix sums: two writes per range update, one prefix sum to read.