RainX_69

Count Subarrays with Equal 0, 1 and 2 | OA | MUST DO

Mar 24th, 2023
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | Source Code | 0 0
  1. https://practice.geeksforgeeks.org/problems/equal-0-1-and-23208/1?page=1&difficulty[]=1&difficulty[]=2&status[]=unsolved&status[]=attempted&category[]=Strings&sortBy=submissions
  2.  
  3. Given a string str of length N which consists of only 0, 1 or 2s, count the number of substring which have equal number of 0s, 1s and 2s.
  4.  
  5. Example 1:
  6.  
  7. Input: str =0102010
  8. Output: 2
  9. Explanation: Substring str[2, 4] =102” and
  10. substring str[4, 6] =201” has equal number
  11. of 0, 1 and 2
  12. Example 2:
  13.  
  14. Input: str =11100022
  15. Output: 0
  16. Explanation: There is no substring with
  17. equal number of 0 , 1 and 2.
  18.  
  19. ---------------------------------------------------------------------------------------------------------------------------------------
  20.  
  21. class Solution{
  22. public:
  23. long long getSubstringWithEqual012(string str) {
  24.         long long count =0;
  25.         map<pair<long long,long long>,long long>mp;
  26.         long long ones =0;
  27.         long long zeros =0;
  28.         long long twos =0;
  29.         mp[{0,0}]=1;
  30.        
  31.         for(int i=0; i<str.length();i++){
  32.             if(str[i]=='1'){
  33.                 ones++;
  34.             }
  35.             if(str[i]=='2'){
  36.                 twos++;
  37.             }
  38.             if(str[i]=='0'){
  39.                 zeros++;
  40.             }
  41.             pair<int,int>p = {zeros-ones,zeros-twos};
  42.             mp[p]++;
  43.         }
  44.         return count;
  45.     }
  46. };
  47.  
Advertisement
Add Comment
Please, Sign In to add comment