Understanding the Problem
We are given an array of integers, and we need to find the longest subarray whose sum is exactly zero.
In simple terms, a subarray is a sequence of consecutive elements from the original array. We want to find the longest one such that all its elements add up to 0.
Why is this tricky?
We could try checking every possible subarray and summing its elements, but that would take too much time. So, we need a smarter way.
Our Step-by-Step Plan
Step 1: Use Prefix Sum
As we go through the array, we keep adding elements to a running total. This is called the prefix sum.
If the same prefix sum appears more than once, it means the elements between those two positions cancel each other out and sum to 0.
Step 2: Use a Hash Map
We use a hash map (or dictionary) to remember the first time we saw each prefix sum. This allows us to quickly calculate the length of any 0-sum subarray.
Let’s Understand with an Example
arr = [15, -2, 2, -8, 1, 7, 10, 23]
Prefix sums as we go:
- Index 0 → 15
- Index 1 → 13
- Index 2 → 15 (again!) → Subarray from index 1 to 2 has sum 0
- Index 3 → 7
- Index 4 → 8
- Index 5 → 15 (again!) → Subarray from index 1 to 5 has sum 0
Longest subarray so far is from index 1 to 5 → length = 5
Covering All Edge Cases
- Case 1: Prefix sum becomes 0 at index i
This means the subarray from index 0 to i itself has sum 0, so the length is i + 1.
- Case 2: Prefix sum repeats
If we saw the same prefix sum earlier, the subarray in between has sum 0.
- Case 3: Prefix sum appears for the first time
We store it in the map with the current index.
- Case 4: No 0-sum subarray exists
If prefix sums are always unique and never zero, the answer is 0.
- Case 5: Entire array sums to 0
If prefix sum is 0 at the last index, the entire array is the answer.
- Case 6: All elements are 0
Each prefix sum is 0, so longest subarray is the entire array.
By using prefix sums and a hash map, we don’t have to check every possible subarray. We just walk through the array once, keeping track of what we’ve seen. This gives us a very efficient O(n) solution that works even for large arrays.
Comments
Loading comments...