Contiguous Subarray Sum Count
Arrays & HashingAuto-graded · 20 test casesLast updated
Tests prefix sum technique with hash maps to count subarrays matching a target sum in linear time
You are given an array of integers nums and a target integer target. Return the total number of contiguous subarrays whose elements sum to target.
A contiguous subarray is a sequence of one or more consecutive elements from the array.
Your solution must run in O(n) time and use O(n) space.
Constraints
1 ≤ nums.length ≤ 10⁵-10⁹ ≤ nums[i] ≤ 10⁹-10⁹ ≤ target ≤ 10⁹- The array may contain negative numbers, zeros, and positive numbers
- Multiple subarrays may overlap
Examples
Example 1
Input: count_target_sum_subarrays([1, 1, 1], 2)
Output: 2
Example 2
Input: count_target_sum_subarrays([1, 2, 3], 3)
Output: 2
Example 3
Input: count_target_sum_subarrays([1, -1, 0], 0)
Output: 3
Hints
Hint 1
Consider how you can use cumulative sums to transform the subarray sum problem into a simpler lookup problem
Hint 2
If the cumulative sum up to index i is S[i], what must the cumulative sum at some earlier index j be for the subarray between j and i to equal the target?
Hint 3
Use a hash map to track how many times each cumulative sum value has appeared as you iterate through the array
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is to use cumulative sums with a hash map. Let S[i] represent the sum of all elements from index 0 up to index i. For any subarray from index j+1 to index i, its sum equals S[i] - S[j].
We want subarrays with sum equal to target, so we need:
S[i] - S[j] = target
Rearranging:
S[j] = S[i] - target
This means: as we compute the running cumulative sum at position i, we can look back and count how many earlier positions had a cumulative sum of exactly running_sum - target. Each such earlier position represents the start of a valid subarray ending at position i.
The algorithm maintains a hash map tracking the frequency of each cumulative sum value encountered so far. For each element:
- Update the running cumulative sum
- Look up how many times
running_sum - targethas been seen (this counts all valid subarrays ending at the current position) - Record the current cumulative sum in the map
We initialize the map with {0: 1} to handle subarrays that start from index 0. This represents an empty prefix with sum 0.
We query the map before inserting the current sum to avoid counting empty subarrays (which would happen if target = 0 and we checked for the current sum matching itself).
This approach works seamlessly with negative numbers because it relies purely on the arithmetic relationship between cumulative sums, not on any monotonicity property. When numbers can be negative, the same cumulative sum value may appear multiple times, which is why we track frequencies rather than just presence.
Time Complexity: O(n) — one pass through the array with O(1) average-time hash map operations per element.
Space Complexity: O(n) — the hash map can store up to n+1 distinct cumulative sum values in the worst case.
from typing import List
def count_target_sum_subarrays(nums: List[int], target: int) -> int:
cumulative_counts = {0: 1}
running_sum = 0
result = 0
for num in nums:
running_sum += num
result += cumulative_counts.get(running_sum - target, 0)
cumulative_counts[running_sum] = cumulative_counts.get(running_sum, 0) + 1
return result