Minimum characters to be replaced to make frequency of all characters same | C ++ implementation to find the Minimum characters to be replaced to make frequency of all characters same ; Function to find the Minimum operations to convert given string to another with equal frequencies of characters ; Frequency of characters ; Loop to find the Frequency of each character ; Sort in decreasing order based on frequency ; Maximum possible answer ; Loop to find the minimum operations required such that frequency of every character is equal ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperations ( string s ) { int freq [ 26 ] = { 0 } ; int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { freq [ s [ i ] - ' A ' ] ++ ; } sort ( freq , freq + 26 , greater < int > ( ) ) ; int answer = n ; for ( int i = 1 ; i <= 26 ; i ++ ) { if ( n % i == 0 ) { int x = n / i ; int y = 0 ; for ( int j = 0 ; j < i ; j ++ ) { y += min ( freq [ j ] , x ) ; } answer = min ( answer , n - y ) ; } } return answer ; } int main ( ) { string s = " BBC " ; cout << minOperations ( s ) ; return 0 ; }