Back to ArraysLongest Subarray With Sum K
Medium

Longest Subarray With Sum K

MediumRecommendedHashingPrefix Sum

Given an array of integers (negative values allowed) and a target k, return the length of the longest contiguous subarray that sums to exactly k.

Examples

Example 1

Input:
nums = [1,-1,5,-2,3], k = 3
Output:
4

Explanation: The subarray [1,-1,5,-2] (indices 0-3) sums to 3 and has length 4 — the longest qualifying subarray.

Example 2

Input:
nums = [-2,-1,2,1], k = 1
Output:
2

Explanation: The subarray [-1,2] (indices 1-2) sums to 1; no longer subarray in this array also sums to 1.

Example 3

Input:
nums = [1,2,3], k = 100
Output:
0

Explanation: No subarray sums to 100, so the answer is 0 — there is no 'no answer' sentinel here, since a length can never be negative.

Constraints

  • 1 <= nums.length <= 2 * 10^5
  • -10^4 <= nums[i] <= 10^4
  • -10^9 <= k <= 10^9

Loading editor…

Code execution is coming soon.