Count the nonempty contiguous ranges whose values add to a requested target sum.
Problem
Input. An integer list nums and an integer target.
Output. Return the number of nonempty contiguous subarrays whose sum equals target.
Rules. Count ranges by their start and end positions; overlapping ranges and identical value sequences count separately. Negative values, zeros, and duplicates are allowed. Do not count the empty range, even for target zero. Leave the input unchanged. Empty input returns zero.
Example. [1, -1, 1, -1, 1] with target zero returns 6.
The valid ranges have lengths two or four. For [1, 1, 1] and target 2, return 2.
Picture
Put a boundary before the array and after each element.
Write the total so far at each boundary: 0, 1, 0, 1, 0, 1.
Two equal totals enclose a zero-sum range. Their positions determine its start and end.
Problem trace
Separate zero-target case: query earlier prefixes before storing the current one
Reference drawing
Problem trace
Count earlier matching prefixes before storing the current prefix
Execution trace
- key 0
- count 1
- next i
- 0
- prefix
- 0
- key 1
- not shown→count 1
- query
- not shown→1 - 0 = 1; prior count 0
- prefix
- 0→1
- key 0
- count 1→count 2
- i
- 0→1
- query
- 1 - 0 = 1; prior count 0→0 - 0 = 0; prior count 1
- key 1
- count 1→count 2
- i
- 1→2
- query
- 0 - 0 = 0; prior count 1→1 - 0 = 1; prior count 1
- key 0
- count 2→count 3
- i
- 2→3
- query
- 1 - 0 = 1; prior count 1→0 - 0 = 0; prior count 2
- key 1
- count 2→count 3
- i
- 3→4
- query
- 0 - 0 = 0; prior count 2→1 - 0 = 1; prior count 2
- Recognize it
- 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.
At a current total prefix, a valid start has total prefix - target.
prefix_count stores how many earlier boundaries have each total.
| Element index | Current total | Earlier matches | New answer |
|---|---|---|---|
| 0 | 1 | 0 | 0 |
| 1 | 0 | 1 | 1 |
| 2 | 1 | 1 | 2 |
| 3 | 0 | 2 | 4 |
| 4 | 1 | 2 | 6 |
The initial {0: 1} represents the boundary before index 0.
Query before inserting the current boundary. Otherwise, target 0 would count an empty range.
Each range is counted once, at its right boundary.
Negative values do not change this subtraction rule.
Code
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
There are additions and expected constant-time map operations. Time is expected and extra space is under bounded-size integer arithmetic. Python integers do not overflow, but larger integers cost more to add and hash.
Change what the map saves
1. Return the longest range
New task: return the maximum length, not the number of ranges.
Picture and change: for a fixed end, the earliest matching start gives the longest range.
Replace counts with earliest indices. Boundary -1 lies before the first element.
The whole replacement function follows.
def longest_sum(nums, target):
earliest = {0: -1}
prefix = best = 0
for index, value in enumerate(nums):
prefix += value
if prefix - target in earliest:
best = max(best, index - earliest[prefix - target])
earliest.setdefault(prefix, index)
return best
Check: longest_sum([1, -1, 1, -1, 1], 0) returns 4.
At index 3, total 0 matches boundary -1, giving length 4.
Overwriting earliest[0] would lose that start.
Use when: the result asks for length. The boundary subtraction stays unchanged.
2. Return whether a range exists
New task: return a boolean for any nonempty matching range.
Picture and change: membership is enough. Replace counts with a set and return on the first match. Still query before inserting. The whole replacement function follows.
def has_sum(nums, target):
seen = {0}
prefix = 0
for value in nums:
prefix += value
if prefix - target in seen:
return True
seen.add(prefix)
return False
Check: has_sum([], 0) is False; has_sum([1, -1], 0) is True.
The second total matches the earlier boundary 0.
Use when: only existence matters. Both alternatives retain expected time and extra space.
Failure case
A set loses repeated starts, so it cannot count all ranges.
For [0, 0], the answer is 3, not 2.
A sliding window also needs a different proof: later negative values can reduce an oversized sum.
Try a changed result
Why is one saved index enough for the longest range but insufficient for the range count?
Check your answer
Counting needs every distinct start. For a fixed end, maximum length needs only the earliest valid start.