Subarray Sum Equals K
Difficulty: Medium · Pattern: Prefix Sum · LeetCode #560
Return the number of contiguous, non-empty subarrays of nums whose elements sum to exactly k. Values may be negative.
Examples
text
nums = [1, 2, 3, -2, 2, 1], k = 3 → 5 ([1,2], [3], [2,3,-2], [3,-2,2], [2,1])
nums = [1, 1, 1], k = 2 → 2Hints
- A sliding window doesn't work with negative numbers. Why?
- sum(l..r) = P[r+1] − P[l]. You want the number of earlier prefixes equal to
P − k. - Initialize the map with {0: 1} so subarrays starting at index 0 count.
Approach
Keep a running prefix sum p and a hash map counting how many times each prefix value has occurred. At each element, every earlier prefix equal to p − k marks the start of a subarray ending here with sum k, so add count[p − k], then record p. Seed with count[0] = 1 for the empty prefix.
Complexity
Time: O(n). Space: O(n).
Python solution
from collections import defaultdict
def subarraySum(nums, k):
count = defaultdict(int)
count[0] = 1
p = ans = 0
for x in nums:
p += x
ans += count[p - k]
count[p] += 1
return ansJavaScript solution
function subarraySum(nums, k) {
const count = new Map([[0, 1]]);
let p = 0, ans = 0;
for (const x of nums) {
p += x;
ans += count.get(p - k) || 0;
count.set(p, (count.get(p) || 0) + 1);
}
return ans;
}