Pattern #07
Prefix Sum
EssentialPrecompute running sums so any range sum is O(1); pair with maps for subarray sum counts.
When to use
Many range-sum queries, or count/find subarrays whose sum equals a target (prefix + hashmap).
Recognition cues
- Range sum queries
- Subarray sum equals K
- Equilibrium / pivot index
- Binary subarrays with sum (0/1 arrays)
Common pitfalls
- Off-by-one between inclusive indices and pref[i+1]
- Forgetting count[0] = 1 for empty-prefix when summing to k
- Overflow in languages with fixed integers (use long in C#)
90-second recognition drill
Which pattern fits best?
- Range sum queries
- Subarray sum equals K
- Equilibrium / pivot index
Interactive
Mental model
A full worked walkthrough of the invariant. Pause, scrub the dots, or use ← →. Aim to narrate each step yourself.
pref = [0, ?, ?, ?, ?]
How to think about it
Build prefix once so any range is one subtraction: sum(i..j) = prefix[j + 1] - prefix[i], with prefix[0] = 0. For how many subarrays sum to k, store how often each prefix appeared. If prefix - k was seen, those earlier positions end a valid subarray here. The same idea with remainders answers divisible by k.
Template shapes
| Shape | Update | Example |
|---|---|---|
| Range query | prefix[i + 1] = prefix[i] + nums[i]. The range is prefix[right + 1] - prefix[left]. The array does not change after the build |
LC 303 |
| Pivot | A running left sum meets total - left - nums[i]. The pivot is in neither side. No such index answers -1 |
LC 724 |
| Count to k | Seed prefix 0 with count 1. At prefix p, add the count of p - k, then record p |
LC 560, LC 930 |
| Remainder | Seed remainder 0. LC 523 maps each remainder to its earliest index and needs the indexes to differ by at least 2. LC 974 keeps a count of size k and adds the count before incrementing it |
LC 523, LC 974 |
Complexity baseline
Build the prefix in O(n). Each range query is O(1). The hashmap and remainder counts are O(n) time. LC 974’s count array is O(k) extra space.
From template to problem
- Keep
prefix[0] = 0. An inclusive range that subtractsprefix[left]without the extra slot is off by one (LC 303). - Seed the empty prefix before the scan: count 1 at sum 0, or index -1 at remainder 0. Forgetting it drops every subarray that starts at index 0.
- Query the prefix, then record it. Recording first counts a length-0 subarray (LC 560). A later copy of the same remainder does not replace the earliest index (LC 523).
- A negative sum has to land in
0 .. k - 1before it is used as an index (LC 974). LC 930’s window formatMost(goal) - atMost(goal - 1)is the same count as the hash.
Template
Same skeleton in TypeScript, Python, and C#. Adapt the invariant; keep the structure.
/** Prefix sum template: O(1) range sum after O(n) build. */
export class NumArray {
private pref: number[];
constructor(nums: number[]) {
this.pref = new Array(nums.length + 1).fill(0);
for (let i = 0; i < nums.length; i++) this.pref[i + 1] = this.pref[i]! + nums[i]!;
}
sumRange(left: number, right: number): number {
return this.pref[right + 1]! - this.pref[left]!;
}
}
/** Prefix sum template: O(1) range sum after O(n) build. */
export class NumArray {
private pref: number[];
constructor(nums: number[]) {
this.pref = new Array(nums.length + 1).fill(0);
for (let i = 0; i < nums.length; i++) this.pref[i + 1] = this.pref[i]! + nums[i]!;
}
sumRange(left: number, right: number): number {
return this.pref[right + 1]! - this.pref[left]!;
}
}
- 1#303 Range Sum Query. ImmutableGuideeasy
- 2#523 Continuous Subarray SumGuidemedium
- 3#560 Subarray Sum Equals KGuidemedium
- 4#724 Find Pivot IndexGuideeasy
- 5#930 Binary Subarrays With SumGuidemedium
- 6#974 Subarray Sums Divisible by KGuidemedium