Detect a Contiguous Subarray with a Target Sum
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: Determine whether an integer array containing negative values has any nonempty contiguous subarray that equals a target, using prefix sums for a linear-time solution.
Constraints
- 0 <= len(nums) <= 200000.
- Every value in nums and target lies in [-10^9, 10^9].
- The input may contain negative values.
- The input array must not be mutated.
- A matching subarray must be non-empty.
- Prefix sums may exceed 32-bit range.
Examples
Input: ([3, -2, 5, -1], 4)
Expected Output: True
Explanation: This is the source example; the contiguous subarray [5, -1] sums to 4.
Input: ([], 0)
Expected Output: False
Explanation: An empty array has no non-empty subarray.
Hints
- Express a subarray sum as the difference between two prefix sums.
- Before adding the current prefix to a set, ask whether current_prefix - target has already appeared.