Prefix sums turn a question about subarrays into a question about pairs of positions: the sum of nums[i..j] is prefix[j+1] - prefix[i]. Combine that with a hash map of prefix sums seen so far, and you can count matching pairs in one pass.
The level of a water tank changes by nums[i] litres during hour i (negative when water is drawn off). Count the stretches of one or more consecutive hours over which the level changes by exactly k in total; that is, return how many contiguous, non-empty subarrays of nums have elements summing to k.
Examples
Input: nums = [3, 1, 2, 4], k = 3
Output: 2
Explanation: [3] and [1, 2].
Input: nums = [1, -1, 0], k = 0
Output: 3
Explanation: [1, -1], [0] and [1, -1, 0].
Constraints
1 <= len(nums) <= 10**4- Elements may be negative, so a sliding window does not work here.
- Aim for O(n) time.
Goals
- Rewrite 'subarray sum equals k' as 'two prefix sums differ by k'
- Count earlier prefix sums with a dictionary instead of looping over them
- Seed the count with prefix 0 so subarrays starting at index 0 are included