Prefix sums: any range total in one subtraction
Asking for the sum of a range again and again means a loop each time, over values you have already added. Add everything up once, keeping the running totals, and every range sum after that is one subtraction.
01 Many range questions, one array
Say you have daily sales for a year and a dashboard that asks for totals: this week, last month, the 30 days before a launch. The direct way loops over the range for every question. With q questions over ranges of up to n days, that is O(n·q) additions, and most of them repeat work done for an earlier question.
def range_sum(a, left, right):total = 0for i in range(left, right + 1): # up to n additionstotal += a[i]return total
# prefix built once: prefix[i] = a[0] + ... + a[i-1]def range_sum(prefix, left, right):return prefix[right + 1] - prefix[left] # 1 subtraction
The right-hand version needs a table built in advance, but only once: O(n) time and n + 1 numbers of memory. After that each query is O(1), whatever the length of the range.
02 Build the running totals once
A prefix sum array stores, at index i, the total of the first i values. Each cell is the previous cell plus one more value, so the whole table takes one pass.
- value added now
- total so far
- cell just filled
- not filled yet
You have a and an empty prefix with one more cell than a. Cell prefix[i] will hold the sum of the first i values.
03 A range total is one subtraction
The total up to the end of a range includes everything before the range too. The total up to the start of the range is exactly that extra part. Take one from the other and only the range is left.
- the range asked for
- the two cells you read
prefix[6] is 3 + 1 + 4 + 1 + 5 + 9. prefix[2] is 3 + 1. Subtracting removes the part before the range and leaves 4 + 1 + 5 + 9 = 19.
04 Why the extra zero at the front
You could store prefix[i] as the sum up to and including a[i], with no leading zero. Then a range that starts at index 0 needs a special case, because there is no cell before it to subtract. The leading 0 is that missing cell.
| Range | Formula | Result |
|---|---|---|
| a[2..5] | prefix[6] - prefix[2] | 23 - 4 = 19 |
| a[0..7] | prefix[8] - prefix[0] | 31 - 0 = 31 |
| a[0..0] | prefix[1] - prefix[0] | 3 - 0 = 3 |
| a[3..3] | prefix[4] - prefix[3] | 9 - 8 = 1 |
The usual bug is reading prefix[right] instead of prefix[right + 1]. With the leading zero, prefix is shifted one place right of a: the sum through a[right] lives at prefix[right + 1]. Test a one-value range such as a[3..3]; it must return a[3].
05 See it in code
Here is the whole thing. build_prefix runs once; range_sum runs for every question.
Python can build the same table with itertools.accumulate(a, initial=0), which also gives the leading zero.
06 Prefix sums plus a hash map
Some questions do not give you the range. How many subarrays sum to `k`? A subarray a[i..j] sums to k exactly when prefix[j + 1] − prefix[i] = k, that is, when an earlier prefix equals the current one minus k. So walk once, keep a running sum, and count how often each prefix sum has appeared in a hash map.
- value read now
- earlier prefix that fits
- prefix just recorded
Count the subarrays of nums that sum to 3. The map of prefix sums seen so far is empty.
This works with negative numbers, where a sliding window does not: a window assumes that growing the range only raises the sum. Prefix sums assume nothing about the values, only that you can subtract.
07 The same trick with other operations
Subtraction is what makes ranges work: it undoes the part before the range. Any operation with a cheap undo gets the same trick. Operations without one need a different tool.
| Operation | Undo | Range in O(1)? |
|---|---|---|
| Sum | subtract | Yes |
| XOR | XOR again (x ^ x = 0) | Yes |
| Count of matches | subtract | Yes, store a running count |
| Product | divide | Only with no zeros; dividing by 0 fails |
| Max or min | none | No: use a sparse table or segment tree |
Product of Array Except Self sidesteps the zero problem: it multiplies a prefix product from the left by a suffix product from the right, so nothing is ever divided.
The idea also grows a dimension. A 2D prefix table stores the sum of the rectangle from the top-left corner, and any rectangle sum is four lookups: P[r2+1][c2+1] − P[r1][c2+1] − P[r2+1][c1] + P[r1][c1].
08 When prefix sums are the wrong tool
a[3] = 10The array changesOne update shifts every prefix after it, so fixing the table is O(n). With many updates and many queries, use a Fenwick tree or segment tree: both do update and range sum in O(log n).int[] prefix = new int[n + 1];Overflow in fixed-size integersTotals grow much bigger than the values. In Java or C++, a running sum of a million values near 2,000,000,000 overflows int; use long. Python integers do not overflow.prefix[right] - prefix[left]Off by oneWith a leading zero the end of the range is right + 1. Drop the + 1 and every answer misses its last value.seen[running] += 1 # before the lookupStoring before looking upIn the count-to-k loop, recording the current prefix first lets it pair with itself when k = 0, counting an empty subarray. Look up first, then record.