
For N = 5, and Arr = {1, -1, 0, 0, 1},
We have the following subarrays with zero sums:
{{1, -1}, {1, -1, 0}, {1, -1, 0, 0}, {-1, 0, 0, 1}, {0}, {0, 0}, {0}}
Among these subarrays, {1, -1, 0, 0} and {-1, 0, 0, 1} are the longest subarrays with their sum equal to zero. Hence the answer is 4.
The first line contains an integer ‘N’, denoting the size of the array ‘Arr’.
The second line contains ‘N’ space-separated integers denoting the elements of ‘Arr’.
You must return an integer representing the length of the longest subarray with a sum equal to zero.
We can iterate over all subarrays of ‘Arr’ and calculate their sum by traversing through the subarray. If the sum of the subarray is found to be zero then we consider the length of the current subarray as a candidate for the maximum length. Finally, we return the length of the longest subarray with zero-sum.
We create the prefix sum array of ‘Arr’. We iterate over all subarrays of ‘Arr’, similar to the brute force approach, but instead of traversing the subarray to find its sum, we use the precalculated prefix sums array to find the sum of the current subarray.
We make the following two observations:
Hence, we use a HashMap to store the first occurrence of an element in ‘PrefixSum’. Then, we iterate over all indices of ‘Arr’ and if the current ‘PrefixSum’ has occurred before, then we take the smallest index at which it occurs to find the longest subarray with zero-sum and ending at the current index. Likewise, we find the length of the longest array with zero-sum.