Length of the Longest Contiguous Subarray Summing to a Target
eBaySoftware Engineer · Technical ScreenLast updated
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.
Given an integer array nums and an integer k, return the length of the longest contiguous subarray whose elements sum to exactly k. If no such subarray exists, return 0.
Function Signature
def longest_subarray_with_sum(nums: list[int], k: int) -> int:
Rules
- A subarray is a non-empty contiguous block
nums[i..j]withi <= j. - Elements may be negative, zero or positive.
- Only the length is returned, so it does not matter which of several longest qualifying subarrays you have in mind.
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
Example 1
Input: nums = [2, -1, 3, 1, -2, 2], k = 3
Output: 5
Both [2, -1, 3, 1, -2] and [-1, 3, 1, -2, 2] sum to 3. The whole array sums to 5, so no subarray of length 6 qualifies.
Example 2
Input: nums = [1, 2, 3], k = 7
Output: 0
The largest possible sum is 6, so no subarray sums to 7.
Example 3
Input: nums = [0, 0, 0], k = 0
Output: 3
The whole array sums to 0.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.