277/670

277. Maximum Size Subarray Sum Equals k

Medium

Given an integer array nums (which may contain negative numbers) and an integer k, find the longest contiguous subarray whose elements sum to exactly k.

Your function receives nums and k and returns a single integer: the length of that longest subarray, or 0 if no subarray sums to k.

Negative numbers rule out a classic sliding window — growing the window can make the sum go either way. Something else scans in one pass.

Example 1:

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

Output: 4

Explanation: The subarray [1, -1, 5, -2] sums to 3 and has length 4 — longer than the other sum-3 subarray [3].

Example 2:

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

Output: 2

Explanation: [-1, 2] sums to 1 with length 2; the single element [1] also works but is shorter.

Constraints:

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

Hints:

Any subarray sum is a difference of two running totals: sum(i..j) = P[j] − P[i−1], where P is the prefix sum. Hunting for a subarray that sums to k is hunting for two prefix values exactly k apart.

Scan left to right with a running sum. If the value prefix − k already appeared as an earlier running sum at index i, then everything after i sums to k. A hash map from prefix value to index answers that in O(1).

For the LONGEST subarray, the map must remember only the FIRST index where each prefix value occurred — never overwrite it. Seed the map with {0: -1} so subarrays starting at index 0 are counted.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

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

Expected output: 4