Maximum Size Subarray Sum Equals k

Medium

Topics
ArrayHash TablePrefix Sum

Given an integer array nums and an integer k, return the maximum length of a subarray that sums to k. If there is no such subarray, return 0.

Example 1

10-1152-2334length 4
The braced run sums to 3 and is the longest that does, length 4.
Cells are the array values; the small numbers underneath are indices.
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.

Example 2

-20-112213length 2
Input:  nums = [-2,-1,2,1], k = 1
Output: 2
Explanation: The subarray [-1,2] sums to 1.

Example 3

102132
No block sums to 100, so the answer is 0.
Input:  nums = [1,2,3], k = 100
Output: 0

Constraints

  • 1 <= nums.length <= 2 * 10^5
  • -10^4 <= nums[i] <= 10^4
  • -2^31 <= k <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls

Intuition

A subarray sums to k exactly when the prefix before it and the prefix after it differ by k. So for each prefix, ask whether the value prefix - k has been seen earlier - and because you want the longest such subarray, remember the earliest index at which each prefix value appeared.

Approach

  1. Keep a running prefix sum and a map from prefix value to its first index. Seed with {0: -1}.
  2. At index i, if prefix - k is in the map, the subarray from first[prefix - k] + 1 to i sums to k - a candidate of length i - first[prefix - k].
  3. Insert the current prefix only if it is absent, keeping the earliest occurrence.
  4. Return the largest candidate, or 0 if none was found.
class Solution:
    def maxSubArrayLen(self, nums, k):
        first = {0: -1}
        total = 0
        best = 0
        for i, v in enumerate(nums):
            total += v
            if total - k in first:
                best = max(best, i - first[total - k])
            if total not in first:
                first[total] = i
        return best

Dry Run

nums = [1, -1, 5, -2, 3], k = 3
Same transformation as contiguous-array: a subarray sums to k exactly when two
prefix sums differ by k, so look up `running - k`.
  i=0  v= 1  running 1                                   record prefix 1 at 0
  i=1  v=-1  running 0                                   0 is already recorded at -1
  i=2  v= 5  running 5                                   record prefix 5 at 2
  i=3  v=-2  running 3   running-k = 0, seen at -1  ->  span 4   best 4
                                                         record prefix 3 at 3
  i=4  v= 3  running 6   running-k = 3, seen at  3  ->  span 1   best 4
                                                         record prefix 6 at 4
answer 4   --  the subarray 1 -1 5 -2 at indices 0..3
Note i=1: the running sum returns to 0, which is already in the map at -1, and
nothing is recorded. Keeping the FIRST index is what maximises every later span,
and it is the only difference from the count-the-subarrays variant, which stores
a frequency instead. Using the wrong one is the classic mix-up between these two
problems.
The {0: -1} sentinel again makes a prefix-length subarray measurable: the answer
here is found against it.
Negative values are the reason a prefix map is required rather than a sliding
window -- the running sum goes down as well as up, so there is no shrink
condition to exploit.

Complexity

  • Time — O(n) — one pass.
  • Space — O(n) for the prefix map.

Common Pitfalls

  • This is the length variant, so store the first index per prefix. Subarray Sum Equals K stores a count instead - using the wrong one is the classic mix-up.
  • Querying the map before inserting the current prefix reads like a correctness requirement and is not one, which is worth knowing before you hunt a bug there. Swapping the two statements changes no answer across 40000 random inputs: when k is 0 the self-match scores a span of 0, and max never lowers the best.
  • Negative numbers rule out a sliding window entirely - do not try to shrink from the left.
  • Prefix sums can exceed 32 bits at the stated limits; use a 64-bit accumulator in Java and C++.

Full Solution — all languages

class Solution:
    def maxSubArrayLen(self, nums, k):
        first = {0: -1}
        running = 0
        best = 0
        for i, v in enumerate(nums):
            running += v
            if running - k in first:
                best = max(best, i - first[running - k])
            if running not in first:
                first[running] = i
        return best
SensAI
Beta
Tap the mic to stop voice mode