The task counts contiguous ranges with an exact sum, values may be negative, and many ranges can end at the same index, so a monotone sliding window is unsafe.
Keep true
Before processing nums[i], the map counts every prefix ending before i. After prefix is updated, count(prefix - target) is exactly the number of valid subarrays ending at i; only then is the current prefix inserted.
Reuse it
Rewrite a range equation as current prefix minus earlier prefix. Store counts when duplicate earlier states represent distinct starts; this also transfers to subarray sums divisible by k and equal-count prefix signatures.
Read it this way: For nums = [1, -1, 1, -1, 1] and target 0, record prefix 0 once before scanning so subarrays starting at index 0 can match. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Pattern: Prefix sum plus hash map.
Simple idea: If the current prefix sum is p, a wanted subarray starts after an earlier
prefix sum of p - target. Store how many times each earlier prefix sum appeared.
This is Two Sum on prefix sums.
def subarray_sum(nums: list[int], target: int) -> int: prefix_count = {0: 1} prefix = 0 answer = 0 for num in nums: prefix += num answer += prefix_count.get(prefix - target, 0) prefix_count[prefix] = prefix_count.get(prefix, 0) + 1 return answer
Cost:O(n) time and O(n) space.
Why the map starts with {0: 1}: A prefix that already equals the target forms a valid
subarray starting at index 0.