KatInterview

Check for Subarray Summing to Target

Arrays & HashingAuto-graded · 20 test cases
MediumAuto-gradedArrays & Hashingprefix-sumhash-setsubarray

Last 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.