Check for Subarray Summing to Target
Arrays & HashingAuto-graded · 20 test casesLast updated
Tests the ability to use prefix sums and a hash set to detect whether any contiguous slice of an array sums to a given value.
Write a function that decides whether an integer array contains at least one contiguous slice whose elements add up to a specified target value.
Your function receives an array of integers (which may include negative numbers) and a target integer. Return True if there exists at least one non-empty contiguous subarray whose sum equals the target, otherwise return False.
Constraints
0 ≤ len(nums) ≤ 200,000- All array values and the target lie in the range
[-10⁹, 10⁹] - You must not modify the input array
- The subarray must contain at least one element (non-empty)
- Array values can be negative, zero, or positive
Examples
Example 1
Input: check_subarray_sum([3, -2, 5, -1], 4)
Output: True
Example 2
Input: check_subarray_sum([], 0)
Output: False
Hints
Hint 1
Think about how you can represent the sum of any slice nums[i..j] using cumulative sums computed from the left.
Hint 2
If you track every cumulative sum you've seen so far in a set, what value would you look for at each step to know a valid slice ends at the current position?
Hint 3
Remember to handle the case where a valid slice starts at index 0—this requires initializing your set with a special value.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to reframe the problem using cumulative sums. Define the cumulative sum at position i as the total of all elements from index 0 up to (but not including) index i, with the cumulative sum at position 0 being 0.
For any slice from index i to index j (inclusive), the sum of that slice equals the cumulative sum at position j+1 minus the cumulative sum at position i. Therefore, a slice ending at position j has sum equal to the target exactly when:
cumulative[j+1] - cumulative[i] = target
Rearranging:
cumulative[i] = cumulative[j+1] - target
This means we can scan through the array once, maintaining a running cumulative sum. At each position, we check whether (current_cumulative - target) has been seen before. If it has, we've found a valid slice. We store each cumulative sum in a hash set as we go.
We initialize the set with 0 to handle slices that start at the very beginning of the array. We check for a match before inserting the current cumulative sum into the set—this ordering guarantees that any match corresponds to a slice containing at least one element (critical when target = 0).
Why It Works
When we find that prefix - target exists in our set, it means some earlier position had that cumulative sum. The elements between that earlier position and the current position form a slice that sums to exactly the target. Since we only check against cumulative sums from strictly earlier positions, the slice is guaranteed to be non-empty.
Complexity
- Time: O(n) where n is the length of the array. We make a single pass, and each hash set lookup and insertion averages O(1).
- Space: O(n) in the worst case, when no matching slice exists and all cumulative sums are distinct.
Solution
from typing import List
def check_subarray_sum(nums: List[int], target: int) -> bool:
seen = {0}
prefix = 0
for value in nums:
prefix += value
if prefix - target in seen:
return True
seen.add(prefix)
return False