text: Minimum operations to make frequency of all characters equal K | C ++ program to convert the given string ; Function to find the minimum number of operations to convert the given string ; Check if N is divisible by K ; Array to store frequency of characters in given string ; Two arrays with number of operations required ; Checking for all possibility ; Driver Code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; void minOperation ( string S , int N , int K ) { if ( N % K ) { cout << " Not ▁ Possible " << endl ; return ; } int count [ 26 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { count [ S [ i ] - 97 ] ++ ; } int E = N / K ; vector < int > greaterE ; vector < int > lessE ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( count [ i ] < E ) lessE . push_back ( E - count [ i ] ) ; else greaterE . push_back ( count [ i ] - E ) ; } sort ( greaterE . begin ( ) , greaterE . end ( ) ) ; sort ( lessE . begin ( ) , lessE . end ( ) ) ; int mi = INT_MAX ; for ( int i = 0 ; i <= K ; i ++ ) { int set1 = i ; int set2 = K - i ; if ( greaterE . size ( ) >= set1 && lessE . size ( ) >= set2 ) { int step1 = 0 ; int step2 = 0 ; for ( int j = 0 ; j < set1 ; j ++ ) step1 += greaterE [ j ] ; for ( int j = 0 ; j < set2 ; j ++ ) step2 += lessE [ j ] ; mi = min ( mi , max ( step1 , step2 ) ) ; } } cout << mi << endl ; } int main ( ) { string S = " accb " ; int N = S . size ( ) ; int K = 2 ; minOperation ( S , N , K ) ; return 0 ; }