Given an array of integers nums and an integer k, return the number of subarrays whose sum equals k.
nums = [1,1,1], k = 22If prefixSum[i] - prefixSum[j-1] = k, then the subarray from index j to i sums to k. Rearranging: prefixSum[j-1] = prefixSum[i] - k. By storing all previous prefix sums in a HashMap, we can check in O(1) how many valid starting points exist for each ending index. The base case map.put(0, 1) handles subarrays starting at index 0.
Checking every subarray is O(n²). And with negatives, growing or shrinking a window tells you nothing.
Use prefix sums. If the running sum now is S, and some earlier prefix was S minus k, the part between them sums to k. So a hash map counts how often each prefix sum has appeared.
A subarray sum is a difference of two prefix sums. Count earlier prefixes equal to sum minus k with a hash map.
Run the animation above on your own input, or watch the 1:18 video explanation of Subarray Sum Equals K with a dry run and Java code.