Largest subarray with 0 sum

 Given an array having both positive and negative integers. The task is to compute the length of the largest subarray with sum 0.

Example 1:

Input:
N = 8
A[] = {15,-2,2,-8,1,7,10,23}
Output: 5
Explanation: The largest subarray with
sum 0 will be -2 2 -8 1 7.


method :

use sorting:

sort both the string now check if the sorted strings are equal if they are equal return 1, else return 0.

c++ implementation:

int maxLen(int a[], int n)
{
    map<int,int>m;int s=0;int mx=0;
    for(int i=0;i<n;i++)
    {
        s=s+a[i];
        if(s==0)
        mx=max(mx,i+1);
        else
        {
            if(m.find(s)!=m.end())
            mx=max(mx,i-m[s]);
            else
            m[s]=i;
        }
        
    }
    return mx;
}


Time Complexity: O(n) 
space Complexity: O(n) 


darkmode