Learn the pattern · ~15 min
Prefix Sum
also called cumulative sum, prefix xor, 2D prefix sums
Keep a running total: the sum of any stretch is this total minus an earlier one, so "a stretch summing to k" becomes "an earlier total equal to cur − k", one hash-map lookup.
Reach for it when you read
- +Many questions of the form "sum of
a[l..r]" on an array that doesn't change. - +Count or find the longest contiguous subarray whose sum is exactly k, especially when values can be negative.
- +"Equal number of A and B": map one to +1 and the other to −1, then look for sum 0.
- +"Sum divisible by k" or "k odd numbers": accumulate a remainder or a 0/1 flag instead of the value.
Not this one when
- ×All values positive and the rule is "sum ≤ k" or "at least k": a sliding window is simpler and O(1) space.
- ×The array changes between queries: a Fenwick or segment tree. A prefix array would need rebuilding.
- ×Many range updates, then one read of the whole array: a difference array, the reverse of a prefix sum.
Learn Prefix Sum
First, what is a "prefix"?
A prefix of an array is a piece taken from the very start. For [3, −1, 4] the prefixes are [] (the empty one), [3], [3, −1] and [3, −1, 4]. A prefix always starts at index 0; only where it stops changes.
A prefix sum is the sum of a prefix. Store all of them in an array P, where P[i] is the sum of the first i elements. P[0] = 0, the sum of the empty prefix.
How do we build it?
Take a = [3, −1, 4, 2, −2, 1]. The rule is one line:
Each prefix sum is the one before it plus the next element:
P[i + 1] = P[i] + a[i].
| i | a[i] | what happens | P[i + 1] |
|---|---|---|---|
| start with the empty prefix | P[0] = 0 | ||
| 0 | 3 | 0 + 3 | P[1] = 3 |
| 1 | −1 | 3 + (−1) | P[2] = 2 |
| 2 | 4 | 2 + 4 | P[3] = 6 |
| 3 | 2 | 6 + 2 | P[4] = 8 |
| 4 | −2 | 8 + (−2) | P[5] = 6 |
| 5 | 1 | 6 + 1 | P[6] = 7 |
So P = [0, 3, 2, 6, 8, 6, 7], one longer than a.
Now the payoff. The sum of any stretch a[l..r] is one subtraction:
sum(a[l..r]) = P[r + 1] − P[l]
P[r + 1] holds everything up to r; P[l] holds everything before l. Take one from the other and only the stretch is left. Check it: a[1..3] is −1 + 4 + 2 = 5, and P[4] − P[1] = 8 − 3 = 5.
The code for it
vector<long long> P(n + 1, 0); // 64-bit: big sums overflow int
for (int i = 0; i < n; i++) P[i + 1] = P[i] + a[i];
// sum of a[l..r] = P[r + 1] - P[l]You don't need to memorise this. It's the table: start at 0, keep adding. One O(n) pass, then every range sum is O(1).
Why the extra slot, P[0] = 0? So that a stretch starting at index 0 needs no special case. a[0..2] is P[3] − P[0] = 6 − 0 = 6. Without the empty prefix you'd need an if (l == 0) everywhere.
Fine, but how does this help us?
Here's the classic problem: Subarray Sum Equals K. Count the stretches whose sum is exactly k.
For [3, −1, 4, 2, −2, 1] and k = 6, solve it by hand. Fix each start and write down the running sum as the stretch grows:
| start | running sums | stretches that hit 6 |
|---|---|---|
| 0 | 3, 2, 6, 8, 6, 7 | [3, −1, 4], [3, −1, 4, 2, −2] |
| 1 | −1, 3, 5, 3, 4 | none |
| 2 | 4, 6, 4, 5 | [4, 2] |
| 3 | 2, 0, 1 | none |
| 4 | −2, −1 | none |
| 5 | 1 | none |
The answer is 3.
The brute force
That's exactly the code: every start, a running sum to every end.
int count = 0;
for (int l = 0; l < n; l++) {
long long s = 0;
for (int r = l; r < n; r++) {
s += a[r];
if (s == k) count++;
}
}About n²/2 stretches, O(n²). For n = 10⁵ that's about 5 × 10⁹ additions. Time limit exceeded.
What about a sliding window? It needs the rule to only get worse as the window grows. Here, adding −1 or −2 lowers the sum, so a window that's too big can become right again. Shrinking is no fix.
The one thought that fixes it
Stop at index 3. The running total from the start is P[4] = 8.
A stretch a[l..3] sums to 6 exactly when P[4] − P[l] = 6, that is, when P[l] = 8 − 6 = 2. So the question "how many stretches end here with sum 6?" becomes "how many earlier prefix sums equal 2?" One did: P[2] = 2, after [3, −1]. The part in between, [4, 2], is the stretch.
So walk once, keep the running total cur, and keep a hash map from each prefix sum to how many times it has appeared. At each step, add seen[cur − k] to the answer.
Two details decide whether it's right.
The seed {0: 1}. At index 2 the total is 6 and we need an earlier prefix equal to 0. That's the empty prefix, the stretch from the very start, [3, −1, 4]. If the map starts empty, both stretches that start at index 0 are missed and the answer drops to 1.
Count before you insert. Look up cur − k first, then add cur to the map. Otherwise, with k = 0, the current prefix would find itself and count an empty stretch. On [3, −3, 1] with k = 0 the answer is 1 ([3, −3]). Inserting first gives 4.
unordered_map<long long, int> seen;
seen[0] = 1; // the empty prefix
long long cur = 0;
int count = 0;
for (int x : a) {
cur += x;
if (seen.count(cur - k)) count += seen[cur - k]; // add how many, not 1
seen[cur]++; // after the lookup
}Dry run
Same array, k = 6.
| x | cur | need cur − 6 | times seen | count | what happens |
|---|---|---|---|---|---|
| 3 | 3 | −3 | 0 | 0 | nothing yet; store 3 |
| −1 | 2 | −4 | 0 | 0 | store 2 |
| 4 | 6 | 0 | 1 (seed) | 1 | [3, −1, 4]; store 6 |
| 2 | 8 | 2 | 1 | 2 | [4, 2]; store 8 |
| −2 | 6 | 0 | 1 (seed) | 3 | [3, −1, 4, 2, −2]; 6 now seen twice |
| 1 | 7 | 1 | 0 | 3 | store 7 |
3, the same answer as the brute force.
Why it's O(n)
Count what happens to each element: it's added to cur once, and causes one lookup and one insert in the hash map, O(1) on average. So n steps of O(1): O(n) time. The map holds at most n + 1 prefix sums: O(n) space.
From O(n²) down to O(n), by turning "which starts work?" into "how many times have I seen cur − k?".
The longest instead of how many? Store the first index
For "the longest stretch with sum k", store the first index where each prefix sum appeared, and never overwrite it: the earliest start gives the longest stretch. The seed becomes {0: −1}, the index just before the array.
if (first.count(cur - k)) best = max(best, i - first[cur - k]);
if (!first.count(cur)) first[cur] = i; // keep the earliestOn our array with k = 6, the longest is 5: [3, −1, 4, 2, −2].
Equal 0s and 1s? Count 0 as −1
Contiguous Array asks for the longest stretch with as many 0s as 1s. Add +1 for a 1 and −1 for a 0; a balanced stretch sums to 0. On [0, 1, 1, 0, 1, 0, 0] the running sums are −1, 0, 1, 0, 1, 0, −1. The running sum 0 at index 5 matches the seed {0: −1}: length 5 − (−1) = 6.
Divisible by k? Compare remainders
Two prefix sums with the same remainder mod k differ by a multiple of k, so the stretch between them is divisible by k. Count equal remainders instead of equal sums, with the same {0: 1} seed.
int r = ((cur % k) + k) % k; // C++ gives -3 % 5 == -3, so fix negativesWith k = 5 the remainders of our prefix sums are 3, 2, 1, 3, 1, 2. Each repeat pairs with the earlier one: 3 stretches ([−1, 4, 2], [2, −2], [4, 2, −2, 1]).
Remember this
- Many range sums on an array that doesn't change: build
Ponce, answerP[r + 1] − P[l]. - Count, or longest, contiguous stretch with sum exactly k, especially with negatives: prefix sum + hash map, not a window.
- Seed the map:
{0: 1}for counting,{0: −1}for lengths. Look up before you insert, and add the stored count, not 1. - Whenever a problem asks "how many subarrays have sum (or balance, or remainder) equal to…", it's this.
Practise it on Running Sum of 1d Array, then Range Sum Query - Immutable (many queries), Find Pivot Index (left total vs right total), Subarray Sum Equals K, Contiguous Array (0 as −1, longest) and Subarray Sums Divisible by K (remainders).
Below, watch Subarray Sum Equals K run line by line.
Watch it work, line by line
Subarray Sum Equals K ↗, nums = [3, 4, 7, 2, -3, 1, 4, 2], k = 7 → 4. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.
When to use it, and when not
Ask yourself
Is this about the sum (or xor, or count) of a stretch, which I could write as this running total minus an earlier one?
Reach for it when
- +many range-sum queries on a static array
- +count subarrays whose sum/xor/mod equals something
- +values may be negative
- +balance problems (map 0 to -1)
- +q up to 2e5 queries
- +array static (if updates happen, use seg-tree)
It fails when
- ×The array is updated between queries; prefix sums go staleuse Fenwick tree or segment tree
- ×Longest/shortest window under a constraint and all numbers are positiveuse Sliding window: simpler, O(1) space
- ×Range min/max: not invertible, no subtraction trickuse Sparse table
- ×Range products with zeros: division is undefineduse Prefix product with explicit zero handling
Looks like it, isn't (and the other way round)
- Subarray Sum Equals K looks like Sliding Window, needs this pattern
Negative numbers make window validity non-monotone; count prefix pairs with a hash map.
- Subarray Sums Divisible by K looks like Sliding Window, needs this pattern
Divisibility is not monotone in window size; key prefix sums by residue.
- Can Make Palindrome from Substring looks like Hash Map / Hash Set Lookup, needs this pattern
Per-query counting is O(26n). Prefix parity masks answer each query by the popcount of an XOR.
Recall card
Answer each one out loud before you open it. Come back in three days and try again without reading the page.
1Why seed the map with
seen[0] = 1?RevealIt's the empty prefix before index 0. Without it, every stretch that starts at the very beginning is missed.
2Why put
seen[cur]++after the lookup, not before?RevealBefore would let the current prefix pair with itself, counting an empty stretch when k = 0.
3Why does a sliding window fail on Subarray Sum Equals K?Reveal
Negative values: growing the window can lower the sum, so it can't decide when to shrink. Prefix sums don't care about signs.
Practice ladder
- 1Running Sum of 1d Arraybuild the prefixEasy
- 2Range Sum Query - Immutablemany range queriesEasy
- 3Find Pivot Indexrunning totalEasy
- 4Subarray Sum Equals Kthe hookMedium
- 5Contiguous Arraylongest, 0 as −1Medium
- 6Subarray Sums Divisible by KremaindersMedium
- 7Continuous Subarray Sumremainders, length ≥ 2Medium
- 8Range Sum Query 2D - Immutabletwo dimensionsMedium
Finished Prefix Sum? Mark it done and Lessgo moves you to the next step.