Complete the code to initialize the count of subarrays to zero.
let count = [1];We start counting subarrays from zero because initially, we have found no subarrays that sum to k.
Complete the code to update the cumulative sum with the current number.
cumulativeSum [1]= num;We add the current number to the cumulative sum to keep track of the sum of elements so far.
Fix the error in checking if (cumulativeSum - k) exists in the map.
if (map.has([1])) { count += map.get(cumulativeSum - k)!; }
We check if (cumulativeSum - k) exists because it means a subarray sums to k ending at the current index.
Fill both blanks to update the map with the current cumulative sum count.
map.set(cumulativeSum, (map.get([1]) || 0) [2] 1);
We update the map by increasing the count of the current cumulative sum by 1.
Fill all three blanks to complete the function that returns the count of subarrays summing to k.
function subarraySum(nums: number[], k: number): number {
let count = 0;
let cumulativeSum = 0;
const map = new Map<number, number>();
map.set(0, 1);
for (const num of nums) {
cumulativeSum [1]= num;
if (map.has(cumulativeSum [2] k)) {
count += map.get(cumulativeSum [2] k)!;
}
map.set(cumulativeSum, (map.get(cumulativeSum) || 0) [3] 1);
}
return count;
}The cumulative sum is updated by adding the current number. We check if (cumulativeSum - k) exists in the map and add its count. Then we update the map by adding 1 to the count of the current cumulative sum.
