Count Contiguous Segments Summing to K
Arrays & HashingAuto-graded · 20 test casesLast updated
Tests efficient subarray counting using prefix sum differences tracked in a hash map.
You are given an array of integers and a target value. Your task is to determine how many contiguous segments (subarrays) within the array have elements that sum exactly to the target value.
A contiguous segment is any sequence of consecutive elements from the array. For example, in [1, 2, 3], the contiguous segments are [1], [2], [3], [1, 2], [2, 3], and [1, 2, 3].
Write a function that takes an integer array and a target integer, then returns the count of all contiguous segments whose elements sum to the target.
Constraints
1 <= nums.length <= 2 * 10^5-1000 <= nums[i] <= 1000-10^7 <= target <= 10^7
Examples
Example 1
Input: count_segments_with_sum([1, 1, 1], 2)
Output: 2
Example 2
Input: count_segments_with_sum([1, 2, 3], 3)
Output: 2
Hints
Hint 1
Consider computing cumulative sums as you iterate through the array. How can earlier cumulative values help count segments ending at the current position?
Hint 2
If a segment from index i+1 to j sums to target, what relationship exists between the cumulative sum at position j and the cumulative sum at position i?
Hint 3
Use a hash map to track how many times each cumulative sum has appeared. Don't forget to handle segments that start from index 0.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is to use cumulative sums combined with a frequency map. As we scan through the array, we maintain a running cumulative sum. At each position j, we want to count how many segments ending at j sum to the target.
If we let cumulative[j] represent the sum from index 0 through j, then a segment from position i+1 through j has sum cumulative[j] - cumulative[i]. We want this to equal the target, which means:
cumulative[j] - cumulative[i] = target
cumulative[i] = cumulative[j] - target
So at position j, we need to count how many earlier positions had a cumulative sum equal to cumulative[j] - target. A hash map tracking the frequency of each cumulative sum value gives us this count in constant time.
The algorithm works as follows:
- Initialize a frequency map with
{0: 1}to handle segments starting at index 0 - Maintain a running cumulative sum as we iterate
- At each position, look up
frequency[cumulative - target]to count valid segments ending here - Update the frequency map with the current cumulative sum
- Sum all the counts
The order matters: we must query the frequency map before updating it with the current cumulative sum. Otherwise, when target equals 0, we would incorrectly match a cumulative sum with itself, counting an empty segment.
Complexity Analysis
Time Complexity: O(n) where n is the length of the input array. We make a single pass through the array, performing constant-time hash map operations at each step.
Space Complexity: O(n) in the worst case. The frequency map can contain up to n distinct cumulative sum values when all elements are positive or all elements have different values.
Solution Code
from collections import defaultdict
from typing import List
def count_segments_with_sum(nums: List[int], target: int) -> int:
frequency = defaultdict(int)
frequency[0] = 1
cumulative = 0
total = 0
for num in nums:
cumulative += num
total += frequency[cumulative - target]
frequency[cumulative] += 1
return total