Subarrays with equal 1s and 0s | Practice | GeeksforGeeks

Given an array containing 0s and 1s. Find the number of subarrays having equal number of 0s and 1s. 
Example 1:
Input:
n = 7
A[] = {1,0,0,1,0,1,1}
Output: 8
Explanation: The index range for the 8 
sub-arrays are: (0, 1), (2, 3), (0, 3), (3, 4), 
(4, 5) ,(2, 5), (0, 5), (1, 6)
Example 2:
Input:
n = 5
A[] = {1,1,1,1,0}
Output: 1
Explanation: The index range for the 
subarray is (3,4).
Your Task:
You don't need to read input or print anything. Your task is to complete the function countSubarrWithEqualZeroAndOne() which takes the array arr[] and the size of the array as inputs and returns the number of subarrays with equal number of 0s and 1s.
Expected Time Complexity: O(n).
Expected Auxiliary Space: O(n).
Constraints:
1 <= n <= 106
0 <= A[i] <= 1
0
shubham211019976 hours ago
 static int countSubarrWithEqualZeroAndOne(int arr[], int n)
   {
      /* Naive Approach
      for(int i=0;i<n;i++){
          if(arr[i]==0) arr[i]=-1;
      }
      int count=0;
      for(int i=0;i<n-1;i++){
          int sum=arr[i];
          for(int j=i+1;j<n;j++){
              sum+=arr[j];
              if(sum==0)count++;
          }
      }
      return count; */
      HashMap<Integer,Integer>h =new HashMap<>();
      for(int i=0;i<n;i++){
          if(arr[i]==0) arr[i]=-1;
      }
      h.put(0,1);
      int count=0;
      int presum=0;
      for(int i:arr){
          presum+=i;
          if(h.containsKey(presum)){
              count+=h.get(presum);
              h.put(presum,h.getOrDefault(presum,0)+1);
          }else{
              h.put(presum,h.getOrDefault(presum,0)+1);
          }
          
      }
      return count;
   }
0
csedeepak2 weeks ago
long long int countSubarrWithEqualZeroAndOne(int arr[], int n)   {       //Your code here       for(int i=0; i<n; i++){           if(arr[i]==0)             arr[i]=-1;       }       int sum=0;       long long cnt=0;       unordered_map<int,int> m;         m[0]=1;       for(int i=0; i<n; i++){           sum += arr[i];            if(m.find(sum) != m.end())                cnt += m[sum];            m[sum]++;       }       return cnt;   }
0
ashish971chauhan2 weeks ago
 int sum = 0;
        int ans = 0;
        
        HashMap<Integer,Integer> map = new HashMap<>();
        map.put(0,1);
        
        for(int i=0;i<n;i++){
            if(arr[i]==0) sum += -1;
            else sum += 1;
            
            if(map.containsKey(sum)){
                ans += map.get(sum);
                map.put(sum , map.get(sum)+1);
            }else{
                map.put(sum,1);
            }
        }
        
        return ans;
0
shresthjaiswal13 weeks ago
Simple Java solution
Test Cases Passed:
203 / 203
Total Time Taken:
1.92/3.23
 
 static int countSubarrWithEqualZeroAndOne(int arr[], int n)   {       // add your code here       for(int i=0;i<n;i++){           if(arr[i] == 0)               arr[i]=-1;       }       HashMap<Integer,Integer> map = new HashMap<>();       int pre_sum=0,count=0;       map.put(0,1);       for(int i=0;i<n;i++){           pre_sum+=arr[i];               if(map.containsKey(pre_sum)){                   count+= map.get(pre_sum);                   map.put(pre_sum,map.get(pre_sum)+1);               }                else{                   map.put(pre_sum,1);               }       }       return count;   }
0
yk95994936811 month ago
map.get(sum)
0
visitant2 months ago
long long int countSubarrWithEqualZeroAndOne(int arr[], int n)
{       //Your code here       unordered_map <int, int> hSumFreq;       unordered_map <int, int> hSubArrs;       long long int sum= 0;       long long int count = 0;                     for(int i=0; i<n; i++)       {           if(arr[i] == 0)           {               sum = sum - 1;           }           else           {               sum = sum + 1;           }           hSumFreq[sum] +=1;           hSubArrs[sum] = (hSumFreq[sum] * (hSumFreq[sum]-1))/2;                      if(sum == 0)           {               count ++;           }       }              for(auto it = hSubArrs.begin(); it!= hSubArrs.end(); it++)       {           count = count + it->second;       }       return count;   }
+1
visitant2 months ago
it is just number of zeroes + NC2 of the repetitions where N is the number of times the prefix sum has occured (greater than 1)
+1
bajpayeevinayak2282 months ago
 
hey,reader this solution vedio link is been give in chechk it out i have commented some line please read,and dry run i was trying hard to get the solution my advice is check this vedio try with code your self and then come to further solution happy coding 
class Solution{ public:   //Function to count subarrays with 1s and 0s.   long long int countSubarrWithEqualZeroAndOne(int arr[], int n)   {       //Your code here       unordered_map<int,int> umap;       int threesum=0;       long long int count=0;       umap[0]++;       for(int i=0;i<n;i++)       {           if(arr[i]==0)           {               threesum+=-1;//adding -1 to threesum if 0 found in array           }           else           {               threesum+=1;//adding -1 to threesum if 0 found in array           }           //auto it=umap.find(threesum);           if(umap.find(threesum)!=umap.end()) ///chech with map if element present that means a there is subarry with equal number of 0/1           {               count+=umap[threesum];               ///umap[threesum]++;           }           umap[threesum]++;       }       return count;          }};
+4
tejshaik2 months ago
c++ sol:
unordered_map<int,long long>mp;       for(int i=0;i<n;i++){           if(arr[i]==0){               arr[i]=-1;           }       }       int sum=0;       mp[sum]++;       for(int i=0;i<n;i++){           sum=sum+arr[i];           mp[sum]++;           if(mp[sum]>1){               co+=mp[sum]-1;           }       }              return co;   }
+2
kashyapjhon2 months ago
C++ Solution:
long long int countSubarrWithEqualZeroAndOne(int arr[], int n)   {       //Your code here       long long sum=0;       long long c=0;       unordered_map<int,int> u;       u.insert({0,1});       for(int i=0;i<n;i++){           if(arr[i]==1){               sum+=1;           }           else{               sum-=1;           }           auto it= u.find(sum);           if(it!=u.end()){               c=c+it->second;               }           u[sum]++;       }       return c;   }
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.