Replace the Substring for Balanced String in C++

C++Server Side ProgrammingProgramming

Suppose we have a string containing only 4 kinds of characters 'Q', 'W', 'E' and 'R'. A string will be balanced if each of its characters appears n/4 times where n is the length of the string. Find the minimum length of the substring that can be replaced with any other string of the same length to make the original string is balanced. So if s = “QQWE”, then output will be 1. This is because we can replace Q to R, so that “RQWE”, that is balanced.

Return 0 if the string is already balanced.

To solve this, we will follow these steps −

  • make one map m
  • for each character in s, store the frequency of characters into map, n := size of s
  • res := n, left := 0
  • for right in range 0 to n – 1
    • decrease m[s[right]] by 1
    • while left < n and m[Q] <= n/4 and m[W] <= n/4 and m[E] <= n/4 and m[R] <= n/4
      • res := minimum of res, right – left + 1
      • increase m[s[left]] by 1
      • increase left by 1
  • return res

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int balancedString(string s) {
      unordered_map <char, int> m;
      for(int i = 0;i<s.size();i++)m[s[i]]++;
      int n = s.size();
      int res = n;
      int left = 0;
      for(int right = 0;right<n;right++){
         m[s[right]]--;
         while(left<n && m['Q']<=n/4 && m['W'] <=n/4 && m['E'] <=n/4 && m['R']<=n/4){
            res = min(res, right - left + 1);
            m[s[left]]+=1;
            left++;
         }
      }
      return res;
   }
};
main(){
   Solution ob;
   cout << (ob.balancedString("QQEQ"));
}

Input

"QQEQ"

Output

2
raja
Published on 02-May-2020 11:27:01
Advertisements