Prefix sums and difference arrays
Store running totals once, and the sum of any subarray becomes one subtraction. Remember earlier running totals in a hash map, and "how many subarrays sum to k?" becomes a single pass.
How to recognise it
- The question is about subarrays (contiguous pieces) and their sums, counts or lengths.
- It asks for the sum of many ranges, which would mean adding the same elements again and again.
- The array can contain negative numbers, so a sliding window that only grows and shrinks will not work.
- XOR or product instead of sum, with the same "everything from i to j" shape.
- Many updates of the form "add v to every element from l to r" (a difference array).
The idea in one picture
Think of a car's odometer. To know how far you drove between the 2nd and 5th stops, you do not add up every metre in between; you read the odometer at both stops and subtract. A prefix sum array is that odometer for an array: the running total up to each position.
prefix[0] = 0
for i from 0 to n - 1:
prefix[i + 1] = prefix[i] + nums[i]
sum of nums[l..r] = prefix[r + 1] - prefix[l] # one subtraction
Counting subarrays with a hash map
A subarray ending at i sums to k exactly when some earlier running total equals running - k. So walk once, and keep a
map of how many times each running total has appeared:
seen = {0: 1} # the empty prefix
running = 0
for x in nums:
running = running + x
count = count + seen[running - k]
seen[running] = seen[running] + 1
Variants change only what the map stores or what you look up:
| Question | Map stores | Look up |
|---|---|---|
| How many subarrays sum to k? | running total → how many times | running - k |
| Longest subarray with sum k? | running total → first index | running - k |
| Any subarray with sum 0? | set of running totals | running itself |
| How many subarrays have XOR k? | running XOR → how many times | running XOR k |
A guided example: how many subarrays of [1, 1, 1] sum to 2?
| x | running | look up running - 2 | found | count | seen afterwards |
|---|---|---|---|---|---|
| (start) | 0 | 0 | {0: 1} | ||
| 1 | 1 | -1 | 0 times | 0 | {0: 1, 1: 1} |
| 1 | 2 | 0 | 1 time | 1 | {0: 1, 1: 1, 2: 1} |
| 1 | 3 | 1 | 1 time | 2 | {0: 1, 1: 1, 2: 1, 3: 1} |
The answer is 2: [1, 1] twice.
Prefix products and difference arrays
The same "precompute from the left" idea works with products. For each position, the product of everything to its left times the product of everything to its right gives "the product of all others" without division.
A difference array is the reverse trick, for updates: to add v to every element from l to r, add v at l and
subtract it at r + 1. After all updates, one running sum turns the differences back into the final array.
Common mistakes
- Forgetting the starting entry for the empty prefix, which misses subarrays that begin at index 0.
- For the longest subarray, overwriting the stored index with later ones. Keep the first index only.
- Adding the current running total to the map before looking up, which can match a subarray of length 0.
- Using a 32-bit running total when long arrays of large values can overflow it.
Problems
- Maximum Size Subarray Sum Equals kmediumguide ready
- Subarray Sum Equals Kmediumguide ready
- Count subarrays with given xor Kmediumguide ready
- Find if there is any subarray with sum equal to 0mediumguide ready
- print all subarrays with 0 summediumguide ready
- Product array Puzzlemediumguide ready