Subarray Sum Equals K
Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. A subarray is a contiguous non-empty sequence of elements within an array.
Sample Input
nums = [1,1,1], k = 2
Sample Output
2
Constraints
- 1 <= nums.length <= 2 * 10^4
- -1000 <= nums[i] <= 1000
- -10^7 <= k <= 10^7
Test Cases
Case 1
Args: [[1,1,1],2]
Expected: 2
Topics
Use a hash map to store prefix sums and their frequencies. At each index, check if currentSum - k exists in the map — if so, those many subarrays ending here sum to k.
function subarraySum(nums, k) {
const prefixCount = new Map([[0, 1]]);
let sum = 0, count = 0;
for (const num of nums) {
sum += num;
if (prefixCount.has(sum - k)) {
count += prefixCount.get(sum - k);
}
prefixCount.set(sum, (prefixCount.get(sum) || 0) + 1);
}
return count;
}
Time: O(n) Space: O(n)
Saved in this browser only. Private to you.