02
Exact sum + hash map (Prefix Sum Sub-pattern)
Find (or count) contiguous ranges whose sum is exactly K. Walk left to right; at each index look up prefix − K in a map of earlier totals.
Signals in the problem statement
- ›
"subarray sum equals K"
- ›
"number of subarrays with sum…"
- ›
negative numbers or zeros allowed
- ›
"zero-sum subarray"
What makes it different
Exact target + negatives is the signal that a sliding window won't work. Zero-sum is the special case K = 0: you're just looking for a total you've seen before.
Questions
ordered from “learn the idea” to “recognise it without help”- 1Subarray with 0 SumWalkthroughEasyBasic Anchor·GeeksforGeeks
- 2Count Subarrays with Zero SumWalkthroughMediumBasic Reinforcement·GeeksforGeeks
- 3Subarray Sum Equals KWalkthroughMediumSlight Variation·LeetCode #560
- 4Binary Subarrays With SumWalkthroughMediumBasic Anchor·LeetCode #930
- 5Path Sum III (prefix sum on a tree)WalkthroughMediumPattern Transfer·LeetCode #437
Template
count-template.cpp
// Count subarrays whose sum is exactly k. Works with negatives and zeros.
long long countSubarrays(vector<int>& nums, int k) {
unordered_map<long long, int> seen; // prefix total -> how many times it appeared
seen[0] = 1; // the empty prefix, for ranges starting at index 0
long long prefix = 0, count = 0;
for (int x : nums) {
prefix += x;
auto it = seen.find(prefix - k); // an earlier total that leaves exactly k between us
if (it != seen.end()) count += it->second;
seen[prefix]++; // insert AFTER the lookup
}
return count;
}Remember this · Prefix Sum
Trigger
Range sums, "subarray sum equals K" (especially with negatives), equal counts, divisible by K.
Think
If I knew the total up to every index, would the answer become a difference of two totals?
Key question
Which earlier prefix value am I looking for when I stand at index i?