To find the longest subarray with sum 0, we need to understand how the prefix sum (running total) can help us track when a subarray cancels itself out.
We traverse the array from left to right and calculate the sum of elements up to each index—this is called the prefix sum. At any point, if the same prefix sum appears again, it means the subarray between those two indices has a sum of 0.
Let’s understand this with different situations:
- Case 1: Prefix sum becomes 0 at index
i
This means the subarray from index 0 to i
itself has a sum of 0. So we update the maximum length to i + 1
.
- Case 2: Prefix sum repeats
If the current prefix sum was seen before at index j
, it means the elements between index j+1
and the current index cancel out to 0. The length of this subarray is i - j
.
- Case 3: Prefix sum is seen for the first time
We store it in a map with its index, so that if it repeats later, we can calculate the subarray length.
- Case 4: No 0 sum subarray exists
In this case, no prefix sum ever repeats, and the sum is never 0. So the answer remains 0.
- Case 5: Entire array has sum 0
This happens when the prefix sum is 0 at the last index. Then the whole array is the longest valid subarray.
- Case 6: Array with all zeros
Every prefix sum is 0 here, so we always get subarrays with 0 sum. The longest one is the entire array.
This approach works well because we don’t have to check every possible subarray. Instead, we use a Hash Map to remember where each prefix sum first appeared and use that to quickly calculate lengths of potential zero-sum subarrays. This gives us a very efficient O(n) time solution.