Longest Subarray With Sum Equal to K

Implement longestSubarrayWithSumK

Given an array of integers nums (which may include negative numbers) and an integer k, find the length of the longest contiguous subarray whose elements sum to exactly k. Return 0 if no such subarray exists. Checking every window works, but re-summing from scratch for every (start, end) pair wastes the fact that a running total only changes by one element at a time. The prefix sumPrefix SumThe running total of all elements from the start of the array up to a given index — precomputing it lets you get the sum of any range in O(1) by subtracting two prefix sums. technique turns this into a single pass: if two prefixes differ by exactly k, the subarray between them sums to k — and a hash map that remembers the first index each prefix sum was seen at finds the longest such subarray in O(n).

Example 1:

Input: nums = [10,5,2,7,1,-10], k = 15

Output: 6

Example 2:

Input: nums = [-5,8,-14,2,4,12], k = -5

Output: 5

Example 3:

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

Output: 0

+ 8 hidden test cases run on Submit.

Constraints:

  • 1 ≤ nums.length ≤ 10⁵
  • -10⁴ ≤ nums[i] ≤ 10⁴
  • -10⁹ ≤ k ≤ 10⁹

nums =

[10, 5, 2, 7, 1, -10]

k =

15