Maximum Size Subarray Sum Equals k
Pattern: Prefix sums and difference arrays
Find the longest subarray summing to k, negatives allowed, by remembering the first index where each running sum appeared.
The problem
You are given an array nums of whole numbers (which may be negative) and a target k. Return the length of the longest
contiguous subarray whose elements add up to k, or 0 if there is none. For example, in [1, -1, 5, -2, 3] with k = 3,
the subarray [1, -1, 5, -2] sums to 3 and has length 4.
The function name maxSubArrayLen matches LeetCode, where this is a premium problem. Running sums can pass the 32-bit
range there, so they are kept in 64 bits.
Think first
- Write the running sums of
[1, -1, 5, -2, 3]. Which two running sums differ by exactly 3? - To make the subarray as long as possible, do you want the earliest or the latest matching start?
- Why can't a sliding window solve this when negative numbers are allowed?
Hints
Brute force, and why it fails
Try every start and extend to every end, keeping a running sum: O(n²). For 200,000 elements that is 2 × 10¹⁰ steps, far too slow. A sliding window does not work either, because with negatives a longer window can have a smaller sum.
The key insight
A subarray's sum is the difference of two running sums. Remembering the first index of every running sum lets each position find its best partner with one look-up.
Dry run
| prefix | 0 |
|---|---|
| best | 0 |
| firstIndex | {0: -1} |
nums = [1, -1, 5, -2, 3] and k = 3. The map remembers the first index of each running sum. The empty prefix has sum 0 at index -1.
The plan
firstIndex = {0: -1}
prefix = 0
best = 0
for i from 0 to n - 1:
prefix = prefix + nums[i]
if prefix - k is in firstIndex:
best = max(best, i - firstIndex[prefix - k])
if prefix is not in firstIndex:
firstIndex[prefix] = i # earliest only
return best
Complexity
- Time
O(n)- Space
O(n)
One pass with average O(1) map operations. The map can hold up to n + 1 running sums.
Edge cases
- No subarray sums to
k: 0. k = 0with zeros, as in[0, 0, 0]: the whole array, length 3.- The whole array sums to
k: found through the entry for index -1.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int maxSubArrayLen(int[] nums, int k) {
Map<Long, Integer> firstIndex = new HashMap<>(); // prefix sum -> first index where it appeared
firstIndex.put(0L, -1); // the empty prefix, before index 0
long prefix = 0;
int best = 0;
for (int i = 0; i < nums.length; i++) {
prefix += nums[i];
Integer start = firstIndex.get(prefix - k); // a subarray (start, i] sums to k
if (start != null) {
best = Math.max(best, i - start);
}
firstIndex.putIfAbsent(prefix, i); // keep the earliest index only
}
return best;
}
}C++
class Solution {
public:
int maxSubArrayLen(vector<int>& nums, int k) {
unordered_map<long long, int> firstIndex; // prefix sum -> first index where it appeared
firstIndex[0] = -1; // the empty prefix, before index 0
long long prefix = 0;
int best = 0;
for (int i = 0; i < static_cast<int>(nums.size()); i++) {
prefix += nums[i];
auto found = firstIndex.find(prefix - k); // a subarray (start, i] sums to k
if (found != firstIndex.end()) {
best = max(best, i - found->second);
}
if (firstIndex.find(prefix) == firstIndex.end()) {
firstIndex[prefix] = i; // keep the earliest index only
}
}
return best;
}
};Python
class Solution:
def maxSubArrayLen(self, nums: list[int], k: int) -> int:
first_index = {0: -1} # prefix sum -> first index; the empty prefix is before index 0
prefix = 0
best = 0
for i, x in enumerate(nums):
prefix += x
if prefix - k in first_index: # a subarray (start, i] sums to k
best = max(best, i - first_index[prefix - k])
if prefix not in first_index:
first_index[prefix] = i # keep the earliest index only
return bestCommon mistakes
- Overwriting the index of a running sum with a later one, which gives shorter subarrays.
- Forgetting
{0: -1}, which misses subarrays starting at index 0. - Using a 32-bit running sum, which can overflow on long inputs.