Complete the code to initialize the count of subarrays to zero.
count = [1]We start counting subarrays from zero because initially we have found none.
Complete the code to update the cumulative sum with the current number.
cumulative_sum [1] numWe add the current number to the cumulative sum to keep track of the total so far.
Fix the error in checking if (cumulative_sum - k) exists in the hash map.
if (cumulative_sum [1] k) in prefix_sums:
We subtract k from cumulative_sum to find if a previous prefix sum exists that forms a subarray summing to k.
Fill both blanks to update the hash map with the current cumulative sum count.
prefix_sums[cumulative_sum] = prefix_sums.get([1], 0) [2] 1
We get the current count of cumulative_sum in the map and add 1 to update it.
Fill all three blanks to complete the function that returns the count of subarrays summing to k.
def subarray_sum(nums, k): count = 0 cumulative_sum = 0 prefix_sums = [1] prefix_sums[0] = 1 for num in nums: cumulative_sum [2] num if (cumulative_sum - k) in prefix_sums: count += prefix_sums[cumulative_sum - k] prefix_sums[cumulative_sum] = prefix_sums.get(cumulative_sum, 0) [3] 1 return count
We use a normal dictionary to store prefix sums, add current number to cumulative_sum, and add 1 to the count in the dictionary.