Largest subarray with 0 sum | Practice | GeeksforGeeks

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.
Your Task:
You just have to complete the function maxLen() which takes two arguments an array A and n, where n is the size of the array A and returns the length of the largest subarray with 0 sum.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 <= N <= 105
-1000 <= A[i] <= 1000, for each valid i
0
lunesco2 hours ago
Python
Total time taken: 0.38/1.46
def maxLen(self, n, arr):
        d = dict()
        suma = 0
        maxi = 0
        
        for i in range(n):
            suma += arr[i]
            
            if suma == 0:
                maxi = i + 1
                continue
            
            if suma not in d:
                d[suma] = i
            else:
                if i - d[suma] > maxi:
                    maxi = i - d[suma]
        
        return maxi
0
19065931 day ago
//JAVA CODE
Time taken is 1.69/2.32
class GfG{   int maxLen(int arr[], int n)   {           HashMap<Integer, Integer> mp = new HashMap<>();//first index will store prefix sum and the second wioll store the index till which the prefix sum is              int sum =0;//variable sum is zero       int maxi =0;//maxmum lenght sub array which will give the sum as 0              for(int i=0 ; i<n ; i++)//linearly iterating the array       {           sum = sum + arr[i];//keep adding the array to the sum                      if(sum == 0)//if it is zero then we can say that the4 sub array from the staring till the current index is giving the sum zero           maxi = i+1;//if you currently standing at index i then it will be i+1 update it                       else           {               if(mp.get(sum)!=null)//if sum is not zero then check that sum does exist in the hash map or not               maxi = Math.max(maxi , i - mp.get(sum));//if it does then get the index though this---> i - mp.get(sum) then compare with previous index if it exceed then update the maxi or els                              else               mp.put(sum , i); //doest not then put it into the hashmap with index where the sum appears           }       }       return maxi;//retun that   }}
0
mayurxxivk1 day ago
CorrectAnswer.⚡
Total Time Taken:1.62/2.32
 
 int maxLen(int arr[], int n)
    {
     
        HashMap<Integer, Integer> mp = new HashMap<>();
        
        int sum =0;
        int maxi =0;
        
        for(int i=0 ; i<n ; i++)
        {
            sum = sum + arr[i];
            
            if(sum == 0)
            maxi = i+1;
            
            else
            {
                if(mp.get(sum)!=null)
                maxi = Math.max(maxi , i - mp.get(sum));
                
                else
                mp.put(sum , i); 
            }
        }
        return maxi;
    }
0
riteshthakare11912 days ago
c++ code:
int maxLen(vector<int>&arr, int n)   {          int maxlen=0;       unordered_map<int,int> m;// prefix-sum,index       m[0]=-1;       int presum=0;              for (int i=0;i<n;i++){           presum+=arr[i];           if (m.find(presum)!=m.end()){               int len=i-m[presum];               if (len>maxlen){                   maxlen=len;               }           }           else{               m[presum]=i;           }       }                     return maxlen;
0
shivaroy0855 days ago
first we can have a intuition that we will keep the sum of the whole array one by one...
 
s = 0
for i in range(n):           s = s+ arr[i]
 
eg:   0    1    2   3     #index
         1 , -1 , 1, -1     #numbers
now at index 1 the sum is zero and at index 3 the sum will be zero  therefore at index 1 the sub array length will be (i+1) i.e 1+1 = 2 and at index 3 the sub array length will be (i+1) i.e 3+1 = 4 
 
max(of them is) 4 so the ans will be 4....
  m = 0         #define before loop statrs
  .....loop....
 
  if s == 0:               m = i+1
 
but if the array is arranged in such a manner that there is no subsequent  element sum which will give 0. then we need to create a hash table to keep the subsequent sum into it with their index, 
 
 
    if we find a repeating sum ones again that means that from the position of that sum number till now the sub array sum is zero, 0
eg:    0   1    2  3   4 
          1   -1  3   2  -2
 from 0th index to 1 index we find sum == 0 then we know that 2 is the max sub array length till now, now on 2nd index we find 3 adding all till 2nd index never gives 0,
we check hash map, 3 not in hash map we insert 3 with the index 2, we continue, we then find  +2 after adding we get 5 , similarly 5 was not in hash map so we add it with index 3, n3xt we add -2 and we again get now, as 3 is already in hash map that means from 2nd index till 4th whatever we added will lead to 0...... BAM!!!!
 
therefore we find the difference (distance )  and check the max of them till now,
               else:                                                  / THIS               if s in dic:                                     /    P                   m = max(m,i-dic[s])              /    A               else:                                              /    R                   dic[s] = i                                   /    T
 
SOLUTION:
 
 
class Solution:   def maxLen(self, n, arr):       #Code here       dic = {}       s = 0       m= 0       for i in range(n):           s = s+ arr[i]           if s == 0:               m = i+1           else:               if s in dic:                   m = max(m,i-dic[s])               else:                   dic[s] = i           return m
0
abhishekmaurya56671 week ago
class Solution{
   public:
   int maxLen(vector<int>&nums, int n)
   {   
       unordered_map<int,int> map;
       int sum=0;
       int len=0;
       map[0]=-1;
       for(int i=0;i<n;i++){
           sum+=nums[i];
          
               if(map.find(sum)!=map.end()){
                   len=max(len,i-(int)map[sum]);
               }
               else{
                   map[sum]=i;
               }
       }
       return len;
       
   }
};
0
abhishekmaurya5667
This comment was deleted.
0
19bcs13141 week ago
class GfG
{
    int maxLen(int arr[], int n)
    {
        // Your code here
        Map<Integer,Integer> map=new HashMap<>();
        int sum=0;
        int len=0;
        map.put(0,-1);
        for(int i=0;i<n;i++){
            sum+=arr[i];
            if(map.containsKey(sum)==false){
                map.put(sum,i);
            }else{
                int index=map.get(sum);
                len=Math.max(len,i-index);
            }
        }
        return len;
    }
}
0
saisaran21 week ago
using unordered map in c++
class Solution{   public:   int maxLen(vector<int>&A, int n)   {          int s=0;       for(int i=0;i<n;i++)       {           s=s+A[i];           A[i]=s;       }       unordered_map<int,int>u;       for(int i=0;i<n;i++)       {           u[A[i]]=i;       }       int mx=0;       for(int i=0;i<n;i++)       {           if(u.find(A[i])!=u.end())           {               mx=max(mx,u[A[i]]-i);           }           if(A[i]==0)           {               mx=max(mx,i+1);           }       }
       return mx;          }};
0
2016yashpratap1 week ago
// Easiest java solution class GfG{   int maxLen(int arr[], int n)     //store sum as key and index as value in the hashmap    {   HashMap<Integer,Integer> hm = new HashMap<>();       int sum =0;       int mlen = 0;       int i =-1;       //initialize hashmap with key =0 and value as -1       hm.put(sum,i);       while(i<arr.length-1)       {    i++;           sum = sum +arr[i];           //if sum is not present in the list then put in the map            if(hm.containsKey(sum)==false)             hm.put(sum,i);            else            {                int len = i - hm.get(sum);                if(len>mlen)                 mlen = len;            }       }       return mlen;          }}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.