Question
Given an array of integers
numsand an integerk, return the total number of subarrays whose sum equals tok.A subarray is a contiguous non-empty sequence of elements within an array.
Ideas
- This is basically glorified Leetcode - 2 Sum using Prefix Sums.
- We want to recognize that the subarray sum of any two indices is just
subarraySum(i)-subarraySum(j)[1, 2, 3, 4]- The sub array sum from j=2 to i =1 is 6 - 1 = 5
- Using this idea, we can get the subarray sum for any index
- The idea here is that we have our sub array sum at
iand we knowk, which means that we want somesubarraySum[i]-subarraySum[j-1]=kwhich represents the sub array sum fromjtoiwherej < i. - Rearranging this, we can see that
subarraySum[j-1] = subarraySum[i]-kwhich means that given our current sum, and our target, we want to see if we have seen a given subarray sum before, if we have then incrementresby its frequency that we are storing in a hash map, otherwise, set that mapping to 1