Minimum characters to be replaced to make frequency of all characters same | Java 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
import java . util . * ; class GFG { static int minOperations ( String s ) { Integer freq [ ] = new Integer [ 26 ] ; Arrays . fill ( freq , 0 ) ; int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { freq [ s . charAt ( i ) - ' A ' ] ++ ; } Arrays . sort ( freq , Collections . reverseOrder ( ) ) ; 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 += Math . min ( freq [ j ] , x ) ; } answer = Math . min ( answer , n - y ) ; } } return answer ; } public static void main ( String [ ] args ) { String s = " BBC " ; System . out . print ( minOperations ( s ) ) ; } }