|
| 1 | +Count total subarrays with equal number of 0s and 1s |
| 2 | + |
| 3 | + |
| 4 | +Brute force: |
| 5 | + |
| 6 | + |
| 7 | +class Solution{ |
| 8 | + public: |
| 9 | + //Function to count subarrays with 1s and 0s. |
| 10 | + long long int countSubarrWithEqualZeroAndOne(int arr[], int n) |
| 11 | + { |
| 12 | + //Your code here |
| 13 | + long long length=0; |
| 14 | + for(int i=0; i<n; i++){ |
| 15 | + for(int j=i; j<n; j++){ |
| 16 | + long long zeroCount=0; |
| 17 | + long long oneCount=0; |
| 18 | + for(int k=i; k<=j; k++){ |
| 19 | + if(arr[k]==0){ |
| 20 | + zeroCount++; |
| 21 | + } |
| 22 | + else{ |
| 23 | + oneCount++; |
| 24 | + } |
| 25 | + |
| 26 | + } |
| 27 | + if(zeroCount==oneCount){ |
| 28 | + length++; |
| 29 | + } |
| 30 | + |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + return length; |
| 35 | + } |
| 36 | +}; |
| 37 | + |
| 38 | + |
| 39 | +Efficient solution: |
| 40 | +Using Hashing |
| 41 | + |
| 42 | + |
| 43 | + |
| 44 | +class Solution{ |
| 45 | + public: |
| 46 | + //Function to count subarrays with 1s and 0s. |
| 47 | + long long int countSubarrWithEqualZeroAndOne(int arr[], int n) |
| 48 | + { |
| 49 | + //Your code here |
| 50 | + unordered_map<int, int> mpp; |
| 51 | + mpp[0]=1; |
| 52 | + long long frequency=0; |
| 53 | + int sum=0; |
| 54 | + for(int i=0; i<n; i++){ |
| 55 | + sum=sum+(arr[i]==1 ? 1 : -1); |
| 56 | + |
| 57 | + if(mpp.find(sum)!=mpp.end()){ |
| 58 | + frequency+=mpp[sum]; |
| 59 | + } |
| 60 | + |
| 61 | + mpp[sum]++; |
| 62 | + } |
| 63 | + |
| 64 | + return frequency; |
| 65 | + } |
| 66 | + |
| 67 | + |
| 68 | +}; |
| 69 | + |
| 70 | +Algroithm: |
| 71 | +1. Create a hash table with key as sum and value as frequency of that sum. |
| 72 | +2. Initialize sum=0 and frequency=0. |
| 73 | +3. Traverse the array and for every element in the array, do the following: |
| 74 | + 1. If the element is 0, then decrease the sum by 1. |
| 75 | + 2. Else, increase the sum by 1. |
| 76 | + 3. If the sum is 0, then increment the frequency by 1. |
| 77 | + 4. If the sum already exists in the hash table, then increment the frequency by the value of that sum in the hash table. |
| 78 | + 5. Increment the value of sum in the hash table by 1. |
| 79 | +4. Return the value of frequency. |
| 80 | + |
| 81 | +TC: O(n) |
| 82 | +SC: O(n) |
| 83 | + |
| 84 | + |
| 85 | +Intuition: |
| 86 | +1. If the intial sum of some part is k, and then if we encouter the same sum later, that means the sum of the elements in between is 0. |
| 87 | + |
| 88 | +k(sum) (equal number of 0s and 1s) |
| 89 | + k(sum) |
0 commit comments