Maximum Size Subarray Sum Equals k

Medium Arrays & Hashing Prefix Sum Strategy

Maximum Size Subarray Sum Equals k is a medium arrays & hashing problem solved with the prefix sum strategy pattern. The best approach, optimal (prefix sums + first-index map), runs in O(n) time and O(n) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (every start, running sum) up.

Problem

You are given an integer array nums, which may contain negative numbers and zeros, and an integer k.

Find the longest contiguous subarray whose elements add up to exactly k, and return its length. A subarray is a run of one or more neighbouring elements. If no subarray has sum k, return 0.

Examples

Example 1

Input
nums = [2,-1,3,1,-2,4], k = 3
Output
5
Why
The first five elements, 2 - 1 + 3 + 1 - 2, add up to 3. Other subarrays also sum to 3, namely [3], [-1,3,1] and [1,-2,4], but none of them is longer than five.

Example 2

Input
nums = [1,1,1], k = 5
Output
0
Why
Even the whole array only sums to 3, so no subarray reaches 5.

Example 3

Input
nums = [-3,4,-1,2,-1], k = 0
Output
3
Why
Both [-3,4,-1] and [-1,2,-1] sum to 0 and have length 3. No longer subarray sums to 0; the whole array sums to 1.

Constraints

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

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 14 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (every start, running sum)O(n²)O(1)
Optimal (prefix sums + first-index map)O(n)O(n)

1Brute force (every start, running sum)

TimeO(n²)Every pair of start and end is visited once, with constant work each.
SpaceO(1)Only a running sum and the best length.

Fix a start i, then extend the end j one step at a time while adding nums[j] to a running sum. Whenever the sum equals k, the subarray i..j is a candidate, and its length j - i + 1 may improve the best answer.

  1. Set best = 0.
  2. For each start i, set sum = 0 and, for each end j from i to n - 1, add nums[j] to sum.
  3. If sum == k, set best = max(best, j - i + 1).
  4. Return best.
class Solution {
    public int maxSubArrayLen(int[] nums, int k) {
        int best = 0;
        for (int i = 0; i < nums.length; i++) {
            long sum = 0;
            for (int j = i; j < nums.length; j++) {
                sum += nums[j];
                if (sum == k) best = Math.max(best, j - i + 1);
            }
        }
        return best;
    }
}

2Optimal (prefix sums + first-index map)

TimeO(n)One pass, with an expected O(1) hash map lookup and insert per element.
SpaceO(n)The map can hold one entry per distinct prefix sum, up to n + 1 of them.

Let prefix be the sum of the first few elements. The subarray from i to j sums to k exactly when the prefix after j minus the prefix before i is k, that is, when an earlier prefix equals prefix - k. Walk the array once with a running prefix and a hash map from each prefix value to the FIRST index after which it appeared, seeded with prefix 0 at index -1 for the empty prefix. At index j, if prefix - k is in the map at index i, the subarray i + 1..j works and has length j - i. Then store the current prefix only if it is new, because keeping the earliest index keeps future subarrays as long as possible.

  1. first = {0: -1}; prefix = 0; best = 0.
  2. For each index j: prefix += nums[j].
  3. If prefix - k is in first, best = max(best, j - first[prefix - k]).
  4. If prefix is not in first yet, set first[prefix] = j.
  5. Return best.
class Solution {
    public int maxSubArrayLen(int[] nums, int k) {
        Map<Long, Integer> first = new HashMap<>();
        first.put(0L, -1);
        long prefix = 0;
        int best = 0;
        for (int j = 0; j < nums.length; j++) {
            prefix += nums[j];
            Integer i = first.get(prefix - k);
            if (i != null) best = Math.max(best, j - i);
            first.putIfAbsent(prefix, j);
        }
        return best;
    }
}

Edge cases to test

  • The whole array sums to k (answer n): the empty prefix must be in the map from the start
  • No subarray sums to k (answer 0)
  • k = 0 with zeros in the array, or with values that cancel out
  • Repeated prefix sums: only the first index of each one gives the longest subarray
  • Negative values, which make a sliding window useless

Hints

Hint 1

With negative numbers, growing a window can make its sum smaller, so the two-pointer window trick does not apply.

Hint 2

The sum of nums[i..j] equals prefix[j + 1] - prefix[i]. You want the farthest-back i for which this equals k.

Hint 3

Walk once, keep the running sum, and store in a hash map the first index where each prefix sum appeared. Never overwrite an entry: an earlier index means a longer subarray.

FAQ

What is the best time complexity for Maximum Size Subarray Sum Equals k?

Optimal (prefix sums + first-index map) runs in O(n) time and O(n) extra space. One pass, with an expected O(1) hash map lookup and insert per element.

Which pattern does Maximum Size Subarray Sum Equals k use?

It is a arrays & hashing problem that uses the prefix sum strategy pattern. Other problems with the same pattern: Subarray Sum Equals K, Subarray with given XOR, Range Sum Query - Immutable.

Is there a brute force solution for Maximum Size Subarray Sum Equals k?

Yes. Brute force (every start, running sum) takes O(n²) time and O(1) space. Fix a start i, then extend the end j one step at a time while adding nums[j] to a running sum.

Which edge cases should I test for Maximum Size Subarray Sum Equals k?

The whole array sums to k (answer n): the empty prefix must be in the map from the start; No subarray sums to k (answer 0); k = 0 with zeros in the array, or with values that cancel out; Repeated prefix sums: only the first index of each one gives the longest subarray; Negative values, which make a sliding window useless.