Length of the Longest Contiguous Subarray Summing to a Target
Company: eBay
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Technical Screen
Overview: Given an integer array that may contain negative numbers and a target k, return the length of the longest contiguous subarray whose sum equals k, or 0 when none exists. Tests reasoning about subarray sums with mixed signs and handling large inputs efficiently.
Constraints
- 1 <= len(nums) <= 2 * 10^5
- -10^4 <= nums[i] <= 10^4
- -10^9 <= k <= 10^9
- Every subarray sum lies within [-2 * 10^9, 2 * 10^9], which fits in a 32-bit signed integer.
Examples
Input: ([2, -1, 3, 1, -2, 2], 3)
Expected Output: 5
Explanation: Source example 1: [2, -1, 3, 1, -2] and [-1, 3, 1, -2, 2] tie at length 5; the whole array sums to 5.
Input: ([1, 2, 3], 7)
Expected Output: 0
Explanation: Source example 2: the largest sum is 6, so no subarray sums to 7.
Hints
- Elements may be negative or zero, so a block's sum can fall as the block grows; do not assume that lengthening a block only increases its sum.
- Only the length is returned: when several different blocks share the maximum length the answer is that length, and when no block sums to k the answer is 0.
- A qualifying block may start at index 0, end at the last index, or cover the whole array; make sure your approach does not miss any of these positions.