Count Contiguous Runs That Add Up to a Goal
Arrays & HashingAuto-graded · 23 test casesLast updated
Count contiguous non-empty subarrays whose elements sum to a goal value, using running prefix sums with a frequency map to handle negatives and zeros in linear time.
You are given a list of integers values and an integer goal. Count how many contiguous, non-empty segments of values have elements that add up to exactly goal.
Segments are distinguished by their position, not by their contents. Two segments with identical contents but at different positions are counted separately. The list may contain negative numbers and zeros, and goal may be negative, zero, or positive.
Return the total number of such segments as an integer.
Constraints
0 <= len(values) <= 2 * 10^4-1000 <= values[i] <= 1000-10^7 <= goal <= 10^7- An empty list contains no non-empty segments, so the answer is
0. - The answer can be as large as
n * (n + 1) / 2. - Aim for O(n) expected time.
Examples
Example 1
Input: count_goal_segments([1, 1, 1], 2)
Output: 2
Example 2
Input: count_goal_segments([1, 2, 3], 3)
Output: 2
Example 3
Input: count_goal_segments([1, -1, 0], 0)
Output: 3
Hints
Hint 1
Express the sum of the segment from index i to j as the difference of two prefix sums.
Hint 2
For each position, ask how many earlier prefix sums equal (current prefix - goal). Each one corresponds to exactly one segment ending here.
Hint 3
Store how many times each prefix sum has occurred, not just whether it occurred, and start the map with prefix 0 seen once so segments beginning at index 0 are counted.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Let P[k] be the sum of the first k elements, with P[0] = 0. The segment from index i to j (inclusive) sums to P[j+1] - P[i]. So a segment ending at index j sums to goal exactly when some earlier prefix P[i] (with i <= j) equals P[j+1] - goal.
Scan left to right while maintaining a dictionary that maps each prefix-sum value to the number of times it has appeared so far. At each element:
- Update the running prefix sum.
- Add to the answer the stored count for
running - goal. This is the number of segments ending at the current index that sum togoal. - Record the current prefix sum in the dictionary.
The dictionary starts as {0: 1}, representing the empty prefix, so segments that begin at index 0 are counted.
Why it is correct
Every non-empty segment corresponds to exactly one pair of prefix positions (i, j+1) with i < j+1. When the scan processes index j, the dictionary holds exactly the prefixes P[0..j], so the lookup counts every valid start i for that end j, and only those. Summing over all j counts each segment exactly once. Because we store frequencies rather than a simple presence flag, repeated prefix values (caused by zeros or by negatives that cancel out) each contribute separately. Nothing in the argument assumes a sign on the elements, so negatives and zeros are handled.
Complexity
- Time: O(n) expected, since each step does a constant number of dictionary operations.
- Space: O(n) for the dictionary in the worst case.
Reference solution
from typing import List
def count_goal_segments(values: List[int], goal: int) -> int:
seen = {0: 1}
running = 0
total = 0
for v in values:
running += v
total += seen.get(running - goal, 0)
seen[running] = seen.get(running, 0) + 1
return total