Prefix Sum Pattern
The Prefix Sum pattern precomputes a cumulative running total of an array so any contiguous range sum can be answered in O(1) time via a single subtraction. Combined with a hash map of seen prefix sums, it counts subarrays with a target sum in a single linear pass. Build is O(n) time and O(n) space; each subsequent range query is O(1).
By Sam K., Founder, InterviewChamp.AI · Last verified
Complexity
- Time
- O(n)
- Space
- O(n)
When to use Prefix Sum
- You face many range-sum queries against an array that does not mutate between queries.
- You need to count or find subarrays whose sum equals (or is divisible by) a target k.
- You are computing 'product of all except self' or any aggregate where each index needs the running combination of everything before or after it.
- The problem extends to 2D and asks for sub-matrix sums — a 2D prefix-sum table answers each rectangle query in O(1).
- You need to detect a continuous subarray whose sum is a multiple of k, using prefix sums modulo k as hash keys.
Template
function subarraySum(nums, k) {
const seen = new Map();
seen.set(0, 1);
let prefix = 0;
let count = 0;
for (const num of nums) {
prefix += num;
if (seen.has(prefix - k)) {
count += seen.get(prefix - k);
}
seen.set(prefix, (seen.get(prefix) || 0) + 1);
}
return count;
}Example LeetCode problems
| # | Problem | Difficulty | Frequency |
|---|---|---|---|
| 560 | Subarray Sum Equals K | medium | foundational |
| 303 | Range Sum Query - Immutable | easy | foundational |
| 304 | Range Sum Query 2D - Immutable | medium | frequently asked |
| 238 | Product of Array Except Self | medium | company favorite |
| 523 | Continuous Subarray Sum | medium | frequently asked |
| 525 | Contiguous Array | medium | frequently asked |
| 724 | Find Pivot Index | easy | foundational |
| 974 | Subarray Sums Divisible by K | medium | classic |
Common mistakes
- Forgetting to seed the hash map with `seen.set(0, 1)` before the loop — subarrays that start at index 0 require an empty-prefix entry to be counted.
- Confusing 'count of subarrays with sum k' (Subarray Sum Equals K) with 'longest subarray with sum k' (a different variant) — the first uses += count, the second uses earliest index.
- Building a prefix array of length n instead of n + 1 and then forgetting to subtract `prefix[i] - prefix[i-1]`, producing off-by-one errors on ranges that include index 0.
- On Product of Array Except Self, computing total product then dividing — fails on inputs containing zero. The correct approach uses two passes (left prefix, right suffix) and avoids division entirely.
- On Continuous Subarray Sum (mod k variant), comparing prefix sums directly instead of `prefix % k`, missing all cases where the difference is a multiple of k but not equal to k itself.
Frequently asked questions
What is the difference between prefix sum and sliding window?
Prefix sum handles arbitrary range queries (any [i, j] pair) and works on arrays with negative numbers via a hash map of seen prefixes. Sliding window only handles contiguous expansion/contraction and typically requires non-negative values so the window's sum is monotonic with size.
Why does the hash-map variant work for Subarray Sum Equals K?
If prefix[j] - prefix[i] = k, then the subarray from i+1 to j sums to k. For each j we ask: how many earlier indices i had prefix[i] = prefix[j] - k? That is one O(1) hash lookup, so the total run is O(n) instead of O(n^2).
How do I extend prefix sum to 2D?
Build a 2D table T where T[i][j] is the sum of the rectangle from (0, 0) to (i, j). Any sub-rectangle sum from (r1, c1) to (r2, c2) is T[r2][c2] - T[r1-1][c2] - T[r2][c1-1] + T[r1-1][c1-1] — inclusion-exclusion over four corners, still O(1) per query after an O(m * n) build.
When does Product of Array Except Self count as a prefix-sum problem?
It is the multiplicative analog. Replace 'sum' with 'product', build a left-product prefix and a right-product suffix, and the answer at index i is leftPrefix[i] * rightSuffix[i]. The structural pattern (cumulative combine + combine inverses) is identical.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.