Given an integer array nums and an integer k, find the number of subarrays whose sum is equal to k.
The solution they gave to this problem (includes negative numbers)
var subarraySum = function(nums, k) {
let counts = new Map();
counts.set(0, 1);
let ans = 0, curr = 0;
for (const num of nums) {
curr += num;
ans += counts.get(curr - k) || 0;
counts.set(curr, (counts.get(curr) || 0) + 1);
}
return ans;
};
I then gave an input of [-3,6,-3,6,-3] and k= 3, but it returns 5 instead of 4. It just so happens that the Map contains key=0, count=2 and adding that 2 in messes things up. I was really trying to understand this maintaining counts of total sums by trying varying arrays.
thanks!
There example of [1, 2, 1, 2, 1] and k=3 works but then I changed it to negatives since that is supposed to be possible.