Find All Contiguous Segments with Target Total
Arrays & HashingAuto-graded · 22 test casesLast updated
Tests prefix sum tracking with hash maps to efficiently count all contiguous subsequences that sum to a target value.
You are given an array of integers and a target sum. Your task is to determine how many contiguous segments of the array add up to exactly the target value.
A contiguous segment is any sequence of consecutive elements from the array. Different positions count as different segments, even if they contain the same values.
Write a function that takes the array and target sum as inputs and returns the count of valid segments.
Constraints
1 <= nums.length <= 2 * 10^4-1000 <= nums[i] <= 1000-10^7 <= k <= 10^7
Notes
- The array may contain negative numbers, zeros, or positive numbers
- If no segments sum to the target, return 0
- A single element forms a valid segment if it equals the target
Examples
Example 1
Input: count_target_sum_segments([1, 1, 1], 2)
Output: 2
Example 2
Input: count_target_sum_segments([1, 2, 3], 3)
Output: 2
Hints
Hint 1
Think about how to avoid checking every possible pair of start and end positions
Hint 2
Consider tracking cumulative sums as you traverse the array
Hint 3
If you know the cumulative sum up to position j and want segments ending at j that sum to k, what cumulative sum would you need at earlier positions?
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The naive solution examines every possible starting and ending position, computing the sum for each segment. This takes O(n²) time, which becomes too slow for arrays with 20,000 elements.
The efficient solution uses cumulative sums with a hash map. A cumulative sum at position j represents the total of all elements from index 0 through j. For any segment from position i to j, the sum equals the cumulative sum at j minus the cumulative sum at position i-1.
If we want a segment ending at j to sum to k, we need:
cumulative[j] - cumulative[i-1] = k
Rearranging:
cumulative[i-1] = cumulative[j] - k
This means: for each position j, we count how many earlier positions had a cumulative sum equal to cumulative[j] - k. Each such earlier position marks the start of a valid segment ending at j.
We maintain a hash map tracking how many times each cumulative sum has occurred. We initialize it with {0: 1} to handle segments starting from index 0 (where there's no prior cumulative sum, conceptually a sum of 0 before the array begins).
For each element:
- Add it to the running cumulative sum
- Look up how many times
running_sum - khas appeared (each occurrence represents a valid segment) - Add the current running sum to the hash map
The order matters: we must look up before inserting the current sum, otherwise we'd incorrectly count empty segments when k equals 0.
Why This Works
Every contiguous segment is uniquely identified by its ending position. When we're at position j, the hash map contains exactly the cumulative sums at all earlier positions (plus the initial 0). Looking up running_sum - k finds all valid starting points for segments ending at j. By processing each position once, we count every valid segment exactly once.
Complexity
Time: O(n) — We make a single pass through the array with constant-time hash map operations at each step.
Space: O(n) — In the worst case, every cumulative sum is unique, requiring n+1 entries in the hash map.
Solution
from typing import List
def count_target_sum_segments(nums: List[int], k: int) -> int:
cumulative_counts = {0: 1}
running_sum = 0
result = 0
for num in nums:
running_sum += num
result += cumulative_counts.get(running_sum - k, 0)
cumulative_counts[running_sum] = cumulative_counts.get(running_sum, 0) + 1
return result