Largest subarray with 0 sum

question–>
https://practice.geeksforgeeks.org/problems/largest-subarray-with-0-sum/1#
code–>

int maxLen(int a[], int n)
{
    unordered_map<int,int> m;
    int pre=0;
    int maxi=INT_MIN;
    for(int i=0;i<n;i++){
        pre+=a[i];
        if(pre==0 ){
            if(m.count(pre)){
                maxi=max(maxi,i+1);
            }
            else{
                m[pre]=i;
            }
        }
        else{
            if(m.count(pre)){
                maxi=max(maxi,i-m[pre]);
            }
            else{
                m[pre]=i;
            }
        }
    }
    
    return maxi==INT_MIN?0:maxi;
}

not passing all testcases

Hey @sheikhhaji18
Because if pre is 0 then max subarray will be from start always i.e a0 +a1+…+ai==0

        if(pre==0 ){
            // if(m.count(pre)){
                maxi=max(maxi,i+1);
            // }
            // else{
            //     m[pre]=i;
            // }
        }

ohh there is no need to insert 0 to hashmap ,okay got it passing all testcases,;

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.