Minimize the number of replacements to get a string with same number of ' a ' , ' b ' and ' c ' in it | CPP program to Minimize the number of replacements to get a string with same number of a , b and c in it ; Function to count numbers ; Count the number of ' a ' , ' b ' and ' c ' in string ; If equal previously ; If not a multiple of 3 ; Increase the number of a ' s ▁ by ▁ ▁ removing ▁ extra ▁ ' b ' and ;c; ; Check if it is ' b ' and it more than n / 3 ; Check if it is ' c ' and it more than n / 3 ; Increase the number of b ' s ▁ by ▁ ▁ removing ▁ extra ▁ ' c ' ; Check if it is ' c ' and it more than n / 3 ; Increase the number of c 's from back ; Check if it is ' a ' and it more than n / 3 ; Increase the number of b 's from back ; Check if it is ' a ' and it more than n / 3 ; Increase the number of c 's from back ; Check if it is ' b ' and it more than n / 3 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string lexoSmallest ( string s , int n ) { int ca = 0 , cb = 0 , cc = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ' a ' ) ca ++ ; else if ( s [ i ] == ' b ' ) cb ++ ; else cc ++ ; } if ( ca == cb && cb == cc ) { return s ; } int cnt = n / 3 ; if ( cnt * 3 != n ) { return " - 1" ; } int i = 0 ; while ( ca < cnt && i < n ) { if ( s [ i ] == ' b ' && cb > cnt ) { cb -- ; s [ i ] = ' a ' ; ca ++ ; } else if ( s [ i ] == ' c ' && cc > cnt ) { cc -- ; s [ i ] = ' a ' ; ca ++ ; } i ++ ; } i = 0 ; while ( cb < cnt && i < n ) { if ( s [ i ] == ' c ' && cc > cnt ) { cc -- ; s [ i ] = '1' ; cb ++ ; } i ++ ; } i = n - 1 ; while ( cc < cnt && i >= 0 ) { if ( s [ i ] == ' a ' && ca > cnt ) { ca -- ; s [ i ] = ' c ' ; cc ++ ; } i -- ; } i = n - 1 ; while ( cb < cnt && i >= 0 ) { if ( s [ i ] == ' a ' && ca > cnt ) { ca -- ; s [ i ] = ' b ' ; cb ++ ; } i -- ; } i = n - 1 ; while ( cc < cnt && i >= 0 ) { if ( s [ i ] == ' b ' && cb > cnt ) { cb -- ; s [ i ] = ' c ' ; cc ++ ; } i -- ; } return s ; } int main ( ) { string s = " aaaaaa " ; int n = s . size ( ) ; cout << lexoSmallest ( s , n ) ; return 0 ; }