A prefix sum array stores running totals: P[i] is the sum of the first i elements. After one O(n) pass, the sum of any range is a single subtraction, O(1). The idea extends to 2D grids, to XOR and other invertible operations, and, combined with a hash map, to counting subarrays with a target sum. Its mirror image, the difference array, makes range updates O(1).
Think of it like
Odometer readings
You never add up every kilometer of a road trip to learn how far it is from Lyon to Turin. You read the odometer in both cities and subtract. A prefix sum array is a list of odometer readings, one per position, so the distance between any two positions is just the difference of two readings.
How it works
Use the half-open convention with a leading zero: P[0] = 0 and P[i + 1] = P[i] + a[i]. Then P has n + 1 entries and the sum of the inclusive range a[l..r] is a single subtraction.
| i | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| a[i] | 3 | 1 | 4 | 1 | 5 | 9 | |
| P[i] | 0 | 3 | 4 | 8 | 9 | 14 | 23 |
How to recognize it
| If the problem says... | Think... |
|---|---|
| Many range-sum queries on an array that does not change | 1D prefix sums: O(n) build, O(1) per query |
| Sum of a sub-rectangle, many times | 2D prefix sums with inclusion–exclusion |
| Count subarrays whose sum equals / is divisible by k | Prefix sum + hash map of earlier prefixes |
| Longest subarray with equal 0s and 1s (or balanced brackets) | Map 0 to −1, then look for equal prefix sums |
| XOR of a subarray, or subarrays with XOR k | Prefix XOR |
| Add v to every element in [l, r], many times, then read the array | Difference array |
| Product of all elements except self | Prefix and suffix products |
2D prefix sums
For a grid, let S[r][c] be the sum of the rectangle from (0, 0) to (r - 1, c - 1), again with an extra row and column of zeros. Building S uses inclusion–exclusion: add the cell, add the rectangle above, add the rectangle to the left, and subtract the top-left overlap that was counted twice.
- 1
Start big
S[r2+1][c2+1]covers everything from the origin to the bottom-right corner of the query. - 2
Cut off the top
Subtract
S[r1][c2+1], the rows above the query. - 3
Cut off the left
Subtract
S[r2+1][c1], the columns to the left of the query. - 4
Repair the corner
The top-left block
S[r1][c1]was subtracted twice, so add it back once.
Prefix sum + hash map
A subarray a[l..r] sums to k exactly when P[r + 1] - P[l] = k, that is, when an earlier prefix equals P[r + 1] - k. So scan left to right, keep a hash map from prefix value to how many times it has occurred, and for each new prefix look up current - k.
| x | prefix | look up prefix − 3 | count added | map after |
|---|---|---|---|---|
| (start) | 0 | {0: 1} | ||
| 1 | 1 | −2 → 0 | 0 | {0: 1, 1: 1} |
| 2 | 3 | 0 → 1 | 1 | {0: 1, 1: 1, 3: 1} |
| 1 | 4 | 1 → 1 | 2 | {..., 4: 1} |
| 2 | 6 | 3 → 1 | 3 | {..., 6: 1} |
| 1 | 7 | 4 → 1 | 4 | {..., 7: 1} |
[1, 2, 1, 2, 1] with k = 3: four subarrays, [1,2], [2,1], [1,2], [2,1].Variations on the same idea
| Problem | Key stored in the map | Value stored |
|---|---|---|
| Subarray Sum Equals K | prefix sum | count of occurrences |
| Subarray Sums Divisible by K | prefix mod k (normalized to be non-negative) | count |
| Continuous Subarray Sum (length ≥ 2) | prefix mod k | earliest index |
| Contiguous Array (equal 0s and 1s) | prefix sum after mapping 0 → −1 | earliest index |
| Maximum length subarray with sum k | prefix sum | earliest index |
Prefix XOR
Prefix sums work for any operation with an inverse. XOR is its own inverse (x ^ x = 0), so with X[0] = 0 and X[i + 1] = X[i] ^ a[i], the XOR of a[l..r] is X[r + 1] ^ X[l]. The hash map trick carries over too: count earlier prefixes equal to current ^ k to count subarrays whose XOR is k.
Difference arrays: range updates in O(1)
A difference array is the inverse of a prefix sum: d[i] = a[i] - a[i - 1]. Adding v to every element of a[l..r] only changes two entries of d: the jump up at l and the jump back down after r. After all updates, one prefix-sum pass rebuilds the array.
| Update | d after the update |
|---|---|
| (start) | [0, 0, 0, 0, 0, 0] |
| +2 on [1, 3] | [0, 2, 0, 0, -2, 0] |
| +3 on [0, 1] | [3, 2, -3, 0, -2, 0] |
| −1 on [2, 4] | [3, 2, -4, 0, -2, 1] |
| prefix sum of d[0..4] | [3, 5, 1, 1, -1] (the final array) |
2D difference arrays
To add v to the rectangle (r1, c1)..(r2, c2), update four corners: D[r1][c1] += v, D[r1][c2+1] -= v, D[r2+1][c1] -= v, D[r2+1][c2+1] += v. A 2D prefix sum over D then produces the final grid. This is how you stamp many rectangles onto a grid (for example "Stamping the Grid" or counting overlapping rectangles) in O(updates + rows × cols).
Choosing a range structure
| Workload | Best tool | Update | Query |
|---|---|---|---|
| Static array, many range sums | Prefix sums | O(n) rebuild | O(1) |
| Many range updates, read once at the end | Difference array | O(1) | O(n) once |
| Point updates mixed with range sums | Fenwick Trees (BIT) | O(log n) | O(log n) |
| Range updates mixed with range queries, or min/max | Segment Trees with lazy propagation | O(log n) | O(log n) |
Complexity
| Operation | Time | Space | Notes |
|---|---|---|---|
| Build 1D prefix sums | O(n) | O(n) | n + 1 entries |
| 1D range sum query | O(1) | O(1) | P[r+1] - P[l] |
| Build 2D prefix sums | O(R × C) | O(R × C) | Extra zero row and column |
| 2D rectangle query | O(1) | O(1) | Four lookups |
| Subarray sum equals k | O(n) | O(n) | Hash map of prefix counts |
| Difference array range update | O(1) | O(n) | Plus one O(n) rebuild |
Prefix sums assume a static array. If values change between queries, use a Fenwick tree or segment tree.
Implementation
Precompute once, answer every query with a constant number of lookups.
class NumArray:
def __init__(self, nums: list[int]):
self.p = [0] * (len(nums) + 1)
for i, x in enumerate(nums):
self.p[i + 1] = self.p[i] + x
def sum_range(self, l: int, r: int) -> int: # inclusive
return self.p[r + 1] - self.p[l]
class NumMatrix:
def __init__(self, grid: list[list[int]]):
rows, cols = len(grid), len(grid[0]) if grid else 0
self.s = [[0] * (cols + 1) for _ in range(rows + 1)]
for r in range(rows):
for c in range(cols):
self.s[r + 1][c + 1] = (grid[r][c] + self.s[r][c + 1]
+ self.s[r + 1][c] - self.s[r][c])
def sum_region(self, r1: int, c1: int, r2: int, c2: int) -> int:
s = self.s
return s[r2 + 1][c2 + 1] - s[r1][c2 + 1] - s[r2 + 1][c1] + s[r1][c1]Key takeaways
- With
P[0] = 0, the sum ofa[l..r]isP[r+1] - P[l]: O(n) to build, O(1) per query. - 2D prefix sums use inclusion–exclusion: subtract the strip above and the strip to the left, add back the corner.
- Prefix sum + hash map counts subarrays with sum k in O(n), even with negative numbers; seed the map with
{0: 1}. - Any invertible operation works, including XOR; min and max do not.
- Difference arrays turn each range update into two point updates, followed by one prefix-sum rebuild.
Common pitfalls
- Off-by-one errors from mixing inclusive and half-open ranges; pick the
n + 1convention and stick with it. - Forgetting to seed the hash map with
{0: 1}, which misses subarrays starting at index 0. - Inserting the current prefix before querying, which counts empty subarrays when k = 0.
- Using negative remainders as map keys in Java, C++ or JavaScript without normalizing.
- Overflowing 32-bit integers in the running sum.
Interview tips
- When you hear "subarray sum equals" or "divisible by", say "prefix sums plus a hash map" and explain the
P[l] = P[r+1] - krewrite. - Contrast with sliding window: prefix sums handle negatives, windows do not.
- For range updates, mention difference arrays first, then Fenwick or segment trees if updates and queries interleave.
Real-world applications
- Summed-area tables (integral images) for fast box filters and Viola-Jones face detection.
- Cumulative distribution functions and percentile lookups.
- Booking and scheduling systems: occupancy per day from many interval reservations (difference arrays).
- Analytics dashboards answering "total between dates" from daily totals.
Practice problems
Test yourself
With P[0] = 0 and P[i+1] = P[i] + a[i], which expression gives the sum of a[2..5] (inclusive)?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.