You are 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.
Example 1:
Input: nums = [2,-1,1,2], k = 2
Output: 4Explanation: [2], [2,-1,1], [-1,1,2], [2] are the subarrays whose sum is equals to k.
Example 2:
Input: nums = [4,4,4,4,4,4], k = 4
Output: 6Constraints:
1 <= nums.length <= 20,000-1,000 <= nums[i] <= 1,000-10,000,000 <= k <= 10,000,000Before attempting this problem, you should be comfortable with:
The simplest approach is to consider every possible subarray and check if its sum equals k. For each starting index, we extend the subarray element by element, maintaining a running sum. Whenever the sum equals k, we count it.
res = 0.i:sum = 0.j from i to n - 1:nums[j] to sum.sum == k, increment res.res.The key insight is that if prefixSum[j] - prefixSum[i] = k, then the subarray from index i+1 to j has sum k. This transforms the problem: for each position, we want to count how many earlier positions have a prefix sum equal to currentPrefixSum - k. A hash map lets us track prefix sum frequencies as we iterate, giving O(1) lookups.
res = 0, curSum = 0, and a hash map prefixSums with {0: 1} (representing the empty prefix).curSum.diff = curSum - k.prefixSums[diff] to res (counts subarrays ending here with sum k).prefixSums[curSum] by 1.res.The hash map must start with {0: 1} to handle subarrays that start from index 0. Without this initialization, subarrays where prefixSum == k from the beginning will not be counted.
Unlike the product variant, this problem allows negative numbers, which means the running sum is non-monotonic. Sliding window does not work here because shrinking the window might increase or decrease the sum unpredictably. The prefix sum + hash map approach is required.
The order of operations matters. You must first check if curSum - k exists in the hash map, then add curSum to the map. Reversing this order would incorrectly count the current element as a valid "previous" prefix sum, leading to wrong results.