Longest subarray with a given sum
25 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)When a problem asks for the longest subarray with sum k (including negative numbers), we still look for an earlier prefix sum equal to currSum - k—but instead of counting how many times it appeared, we want the earliest index where it appeared.
Storing only the first index
Suppose at index i, our running prefix sum is currSum (covering nums[0 .. i]).
- Create Map<Long, Integer> firstIndex = new HashMap<>() and put (0L, -1).
- Initialize long currSum = 0 and int maxLen = 0.
- For i = 0 .. nums.length - 1: currSum += nums[i].
- If firstIndex.containsKey(currSum - k), update maxLen = Math.max(maxLen, i - firstIndex.get(currSum - k)).
- Call firstIndex.putIfAbsent(currSum, i) so only the earliest index for currSum is kept.
Example 1 · Brute force: running sum from every start, keep the longest (O(n²) time, O(1) space)
public class MaxSubArrayLenBrute { public static int maxSubArrayLen(int[] nums, int k) { int maxLen = 0; for (int start = 0; start < nums.length; start++) { long sum = 0; for (int end = start; end < nums.length; end++) { sum += nums[end]; if (sum == k) { maxLen = Math.max(maxLen, end - start + 1); } } } return maxLen; }
public static void main(String[] args) { int[] a = {1, -1, 5, -2, 3}; System.out.println("Longest sum=3 in [1,-1,5,-2,3]: " + maxSubArrayLen(a, 3)); int[] b = {-2, -1, 2, 1}; System.out.println("Longest sum=1 in [-2,-1,2,1]: " + maxSubArrayLen(b, 1)); }}Longest sum=3 in [1,-1,5,-2,3]: 4 Longest sum=1 in [-2,-1,2,1]: 2
What this code does
- Every start and end pair is checked, so the work is about n² / 2 additions.
- For a fixed end, only the earliest start with the right prefix sum gives the longest subarray, and a map can hold that earliest index.
Example 2 · Optimal: map from prefix sum to its first index (O(n) time, O(n) space)
import java.util.HashMap;import java.util.Map;
public class MaxSubArrayLenSumKDemo { public static int maxSubArrayLen(int[] nums, int k) { Map<Long, Integer> firstIndex = new HashMap<>(); firstIndex.put(0L, -1); long currSum = 0; int maxLen = 0;
for (int i = 0; i < nums.length; i++) { currSum += nums[i]; long need = currSum - k; if (firstIndex.containsKey(need)) { maxLen = Math.max(maxLen, i - firstIndex.get(need)); } firstIndex.putIfAbsent(currSum, i); } return maxLen; }
public static void main(String[] args) { int[] a = {1, -1, 5, -2, 3}; System.out.println("Longest sum=3 in [1,-1,5,-2,3]: " + maxSubArrayLen(a, 3)); int[] b = {-2, -1, 2, 1}; System.out.println("Longest sum=1 in [-2,-1,2,1]: " + maxSubArrayLen(b, 1)); }}Longest sum=3 in [1,-1,5,-2,3]: 4 Longest sum=1 in [-2,-1,2,1]: 2
What this code does
- In [1, -1, 5, -2, 3], at i = 0 currSum is 1 (stored at 0). At i = 1 currSum is 0, but 0 is ALREADY in firstIndex at -1, so putIfAbsent keeps 0 -> -1!
- At i = 3, currSum is 3, matching need = 3 - 3 = 0 at index -1 for length 3 - (-1) = 4 ([1, -1, 5, -2]).
- Why it is faster: for each end index one lookup finds the earliest matching start, instead of trying every start.
If an earlier prefix nums[0 .. j] had sum currSum - k, then the subarray nums[j + 1 .. i] has sum k and length:
length = i - j
To make i - j as large as possible, we need j to be as small (early) as possible!
Therefore, we maintain Map<Long, Integer> firstIndex seeded with firstIndex.put(0L, -1) (because the empty prefix before index 0 ends at virtual index -1, so a valid prefix nums[0 .. i] has length i - (-1) = i + 1). When currSum is computed at index i, we record firstIndex.putIfAbsent(currSum, i) so a later duplicate of currSum never overwrites the earlier index!
Find the bug
Find the first-index bug
Tap the line that is wrong.
This code returns lengths that are too short. Which line is wrong?
Round 1 of 2Zero-sum subarrays
A zero-sum subarray is the special case k = 0 (Largest Subarray with 0 Sum). When k = 0, currSum - k is just currSum!
int[] nums = {3, 4, -7, 1, 2, -3};Map<Long, Integer> firstIndex = new HashMap<>();firstIndex.put(0L, -1); // seed: the empty prefixlong currSum = 0;int best = 0;for (int i = 0; i < nums.length; i++) { currSum += nums[i]; if (firstIndex.containsKey(currSum)) { best = Math.max(best, i - firstIndex.get(currSum)); // same sum again: zero-sum gap } else { firstIndex.put(currSum, i); // keep only the first index }}// prefix sums 3, 7, 0, 1, 3, 0 -> best = 6 (the whole array sums to 0)That means a contiguous subarray nums[j + 1 .. i] has sum 0 if and only if the running prefix sum at index i is identical to the running prefix sum at an earlier index j (P[i] == P[j]).
Intuitively, if your bank balance was ₹500 on Monday (j) and is ₹500 again on Friday (i), then the net sum of all transactions between Monday and Friday must be zero!
- If currSum repeats a value seen at firstIndex.get(currSum), the subarray between them sums to 0.
- If currSum == 0 at index i, it matches the seed (0L -> -1), giving length i - (-1) = i + 1.
Equal numbers of 0s and 1s
In Contiguous Array, given a binary array nums of 0s and 1s, we want the maximum length of a contiguous subarray with an equal number of 0s and 1s.
Example 3 · Contiguous Array: longest subarray with equal 0s and 1s
import java.util.HashMap;import java.util.Map;
public class ContiguousArrayDemo { public static int findMaxLength(int[] nums) { Map<Integer, Integer> firstIndex = new HashMap<>(); firstIndex.put(0, -1); int balance = 0; int maxLen = 0;
for (int i = 0; i < nums.length; i++) { balance += (nums[i] == 1) ? 1 : -1; if (firstIndex.containsKey(balance)) { maxLen = Math.max(maxLen, i - firstIndex.get(balance)); } else { firstIndex.put(balance, i); } } return maxLen; }
public static void main(String[] args) { int[] a = {0, 1, 0}; System.out.println("[0, 1, 0] -> " + findMaxLength(a)); int[] b = {0, 0, 1, 0, 0, 0, 1, 1}; System.out.println("[0,0,1,0,0,0,1,1] -> " + findMaxLength(b)); }}[0, 1, 0] -> 2 [0,0,1,0,0,0,1,1] -> 6
What this code does
- Mapping 0 -> -1 and 1 -> +1 turns equal counts of 0s and 1s into a net balance change of 0.
- In [0,0,1,0,0,0,1,1], balance is -2 at i = 1 and returns to -2 at i = 7, giving length 7 - 1 = 6.
Example 4 · Longest subarray with equal even and odd numbers, returning the subarray
import java.util.Arrays;import java.util.HashMap;import java.util.Map;
public class EqualEvenOddSubarrayDemo { public static int[] longestEqualEvenOdd(int[] nums) { Map<Integer, Integer> firstIdx = new HashMap<>(); firstIdx.put(0, -1); int bal = 0, maxLen = 0, bestStart = 0;
for (int i = 0; i < nums.length; i++) { bal += ((nums[i] & 1) == 0) ? 1 : -1; if (firstIdx.containsKey(bal)) { int len = i - firstIdx.get(bal); if (len > maxLen) { maxLen = len; bestStart = firstIdx.get(bal) + 1; } } else { firstIdx.put(bal, i); } } return Arrays.copyOfRange(nums, bestStart, bestStart + maxLen); }
public static void main(String[] args) { int[] nums = {2, 4, 1, 6, 3, 5, 8}; System.out.println(Arrays.toString(longestEqualEvenOdd(nums))); }}[2, 4, 1, 6, 3, 5]
What this code does
- When bal matches firstIdx.get(bal) = j, the balanced subarray is nums[j + 1 .. i] of length i - j.
- Here indices 0..5 ([2, 4, 1, 6, 3, 5]) is the first subarray of maximum length 6 with three evens (2, 4, 6) and three odds (1, 3, 5).
- Treat 1 as +1 and 0 as -1: balance += (nums[i] == 1 ? 1 : -1).
- Equal 0s and 1s in [j + 1 .. i] <-> balance at i equals balance at j.
- Seed firstIndex.put(0, -1) and use putIfAbsent(balance, i).
How do we turn "equal number of 0s and 1s" into a prefix-sum problem? Treat every 0 as -1 and every 1 as +1!
Then any subarray with m zeroes and m ones has sum m(-1) + m(+1) = 0. The problem immediately reduces to Longest Zero-Sum Subarray! This +1 / -1 balance trick works for any two-category balance problem: equal vowels and consonants, equal evens and odds, or longest well-performing interval.
Next step
Check your understanding
10 quick questions