Subarray Sum Equals K
Problem (restated)
Given an array of integers and an integer k, return the total number of continuous subarrays whose sum equals k.
Intuition
Prefix sums: count how often (pref - k) has occurred. Each such earlier prefix forms a valid subarray ending here.
Approaches
Prefix sum + hash map
UnverifiedIdea. count[0]=1. Walk array updating pref; ans += count[pref-k]; count[pref]++.
Walkthrough. nums=[1,1,1], k=2 → subarrays [1,1] twice → answer 2.
Trade-offs. Handles negatives (sliding window does not). Must seed count[0]=1.
export function subarraySum(nums: number[], k: number): number {
const count = new Map<number, number>([[0, 1]]);
let pref = 0, ans = 0;
for (const x of nums) {
pref += x;
ans += count.get(pref - k) ?? 0;
count.set(pref, (count.get(pref) ?? 0) + 1);
}
return ans;
}
export function subarraySum(nums: number[], k: number): number {
const count = new Map<number, number>([[0, 1]]);
let pref = 0, ans = 0;
for (const x of nums) {
pref += x;
ans += count.get(pref - k) ?? 0;
count.set(pref, (count.get(pref) ?? 0) + 1);
}
return ans;
}
Template connection
Prefix sum + hashmap from the Prefix Sum template.
Reflection
count[pref - k]is how many earlier prefixes make this difference. Why seedcount[0] = 1?- Negatives break a sliding window. Why does the hash map still work?
k = 0and the array is all zeros: how many subarrays qualify?