Tally Contiguous Segments Matching a Goal Total
Arrays & HashingAuto-graded · 20 test casesLast updated
Count contiguous non-empty segments of an integer array whose sum equals a goal, using running totals and a frequency map to handle negatives and zeros in linear time.
Tally Contiguous Segments Matching a Goal Total
You are given a list of integers values and an integer goal. Determine how many contiguous segments of values have elements that add up to exactly goal.
A segment is a non-empty run of neighboring elements taken in their original order. Two segments are considered different if they have different start or end positions, even if they contain identical numbers. Overlapping segments are each counted separately.
Input
values: a list of integers.goal: an integer.
Output
Return a single integer: the number of segments values[i..j] (with 0 <= i <= j < len(values)) whose sum equals goal.
Notes
- Elements may be negative, zero, or positive, so running totals do not always grow in one direction.
- Segments that begin at index
0must be counted. - Arrays containing many zeros can produce many overlapping segments with the same sum; all of them count.
Constraints
1 <= len(values) <= 10^5-1000 <= values[i] <= 1000-10^7 <= goal <= 10^7
Examples
Example 1
Input: count_segments_with_total([1, 1, 1], 2)
Output: 2
Example 2
Input: count_segments_with_total([1, -1, 0], 0)
Output: 3
Hints
Hint 1
Think about the running total up to each position. How can the sum of a segment be written as a difference of two running totals?
Hint 2
For each end position, you need the number of earlier running totals equal to (current total - goal). What data structure answers 'how many times have I seen this value' in O(1)?
Hint 3
Seed your frequency map with the empty running total 0, and look up the needed value before recording the current total, so that empty segments are never counted.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Define the running total P[k] as the sum of the first k elements, with P[0] = 0. The sum of the segment from index i to j equals P[j+1] - P[i]. This segment hits goal exactly when P[i] = P[j+1] - goal.
So, for each end position, we only need to know how many earlier running totals equal current_total - goal. We sweep the array once while keeping a hash map from each running total to how many times it has appeared.
For each element:
- Add it to the running total.
- Add
seen[running - goal]to the answer. - Increment
seen[running].
The map starts as {0: 1}, representing the empty prefix, so that segments starting at index 0 are counted.
Why it is correct
Valid segments correspond one-to-one with pairs of prefix positions (a, b), a < b, where P[b] - P[a] = goal. When we handle position b, the map contains exactly the totals P[0..b-1], so the lookup counts every valid a for that b and nothing else. Looking up before inserting prevents a prefix from pairing with itself, which would count an empty segment when goal = 0.
A sliding window does not work here because negative values mean the window sum is not monotonic in either pointer. The hash-map count does not rely on monotonicity.
Complexity
- Time: O(n), one pass with O(1) average hash operations.
- Space: O(n) for up to n + 1 distinct running totals.
Reference solution
from collections import defaultdict
from typing import List
def count_segments_with_total(values: List[int], goal: int) -> int:
seen = defaultdict(int)
seen[0] = 1
running = 0
answer = 0
for v in values:
running += v
answer += seen[running - goal]
seen[running] += 1
return answer