Find the maximum length of a subarray whose sum is 0.
Problem Statement
Given an array `arr` of integers, find the length of the longest sub-array with sum equal to `0`.
Examples
Input: arr = [15, -2, 2, -8, 1, 7, 10, 23]
Output: 5
Explanation: The largest subarray with sum 0 is [-2, 2, -8, 1, 7] whose length is 5.
Input: arr = [2, 10, 4]
Output: 0
Explanation: Combining the input according to Largest Subarray with Sum 0 logic yields 0.
Complexity
Time Complexity: O(N)
Space Complexity: O(N)
Hints
š” Hint 1:
If cumulative sum at index i equals cumulative sum at index j, the subarray between j+1 and i sums to 0.
š” Hint 2:
Store the first occurrence index of each prefix sum in a hash map.
š” Hint 3:
If currentSum is 0, subarray from 0 to i sums to 0 (length = i + 1).
Editorial & Approach
Problem Overview & Intuition
A subarray [j + 1 ... i] has sum 0 if and only if prefixSum[i] === prefixSum[j]. Storing the earliest occurrence of each prefix sum in a map allows maximizing i - j in linear O(N) time.
Step-by-Step Approach
- Initialize
map = new Map(),maxLen = 0,currentSum = 0. - Iterate
ifrom0toarr.length - 1. - Accumulate
currentSum += arr[i]. - If
currentSum === 0,maxLen = i + 1. - If
map.has(currentSum), updatemaxLen = Math.max(maxLen, i - map.get(currentSum)). - Else, store
map.set(currentSum, i). - Return
maxLen.
Optimal Implementation (JavaScript)
function maxLenSubarrayZeroSum(arr) {
const map = new Map();
let maxLen = 0, currentSum = 0;
for (let i = 0; i < arr.length; i++) {
currentSum += arr[i];
if (currentSum === 0) maxLen = i + 1;
if (map.has(currentSum)) maxLen = Math.max(maxLen, i - map.get(currentSum));
else map.set(currentSum, i);
}
return maxLen;
}
Complexity Analysis
Time Complexity
O(N) ā single traversal with O(1) average hash map lookups.
Space Complexity
O(N) ā prefix sum map.
Edge Cases & Corner Traps Handled
- No subarray sums to 0: returns 0.
- Entire array sums to 0: returns arr.length.
- Single element array [0]: returns 1.