Arrays & Hashing · Pattern 10 of 26
Prefix sums
prefix[i] = sum of the first i values, so any subarray sum is a difference of two prefixes. With a hash map of earlier prefixes you can count subarrays with an exact sum, remainder or XOR in one pass.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Many range-sum queries on a fixed array
- Count subarrays whose sum equals k or is divisible by k
- Negative numbers present (a sliding window will not work)
- Balance problems: equal 0s and 1s, equal vowels
The template
int subarraySum(int[] nums, int k) { // subarrays with sum exactly k
Map<Integer, Integer> seen = new HashMap<>(); // prefix sum -> how many times
seen.put(0, 1); // the empty prefix
int sum = 0, count = 0;
for (int x : nums) {
sum += x;
count += seen.getOrDefault(sum - k, 0); // earlier prefixes that leave exactly k
seen.merge(sum, 1, Integer::sum);
}
return count;
} def subarray_sum(nums, k): # subarrays with sum exactly k
seen = {0: 1} # prefix sum -> how many times (empty prefix)
total = count = 0
for x in nums:
total += x
count += seen.get(total - k, 0) # earlier prefixes that leave exactly k
seen[total] = seen.get(total, 0) + 1
return count int subarraySum(vector<int>& nums, int k) { // subarrays with sum exactly k
unordered_map<int, int> seen{{0, 1}}; // prefix sum -> how many times
int sum = 0, count = 0;
for (int x : nums) {
sum += x;
auto it = seen.find(sum - k); // earlier prefixes that leave exactly k
if (it != seen.end()) count += it->second;
seen[sum]++;
}
return count;
} function subarraySum(nums, k) { // subarrays with sum exactly k
const seen = new Map([[0, 1]]); // prefix sum -> how many times
let sum = 0, count = 0;
for (const x of nums) {
sum += x;
count += seen.get(sum - k) ?? 0; // earlier prefixes that leave exactly k
seen.set(sum, (seen.get(sum) ?? 0) + 1);
}
return count;
} The variations
-
1Range sums from a prefix array
Build prefix once, then sum(l..r) = prefix[r + 1] − prefix[l] in O(1). Pivot index, minimum start value, candles between plates and shop penalty all read prefixes.
Now you solve -
2Count subarrays with a sum
Look up
sum − kamong earlier prefixes. For "equal 0s and 1s", count 0 as −1 and look for equal prefixes.Now you solve -
3Remainders mod k
Two prefixes with the same remainder enclose a subarray divisible by k. Store the remainder instead of the sum.
Now you solve -
4Prefix XOR and bitmasks
XOR works like a sum: xor(l..r) = prefix[r + 1] ^ prefix[l]. A bitmask of odd/even letter counts is a prefix XOR too.
Now you solve -
5More practice
More problems that use this pattern. Try them once the variations above feel easy.
Problems
Mistakes to avoid
- Forgetting the empty prefix (
0 → 1), which misses subarrays that start at index 0. - Updating the map before checking it, which counts the empty subarray when k = 0.
- Negative remainders in Java, C++ and JS: use
((sum % k) + k) % k.
Lesson done
Next: Sliding window of a fixed size →Mark it done once you can write the template from memory and you have solved the worked examples yourself.