text: Minimum operations to make frequency of all characters equal K | 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: function minOperation ( S , N , K ) { if ( N % K ) { document . write ( " " ) ; return ; } var count = Array ( 26 ) . fill ( 0 ) ; for ( var i = 0 ; i < N ; i ++ ) { count [ S [ i ] . charCodeAt ( 0 ) - 97 ] ++ ; } var E = N / K ; var greaterE = [ ] ; var lessE = [ ] ; for ( var i = 0 ; i < 26 ; i ++ ) { if ( count [ i ] < E ) lessE . push ( E - count [ i ] ) ; else greaterE . push ( count [ i ] - E ) ; } greaterE . sort ( ) ; lessE . sort ( ) ; var mi = 1000000000 ; for ( var i = 0 ; i <= K ; i ++ ) { var set1 = i ; var set2 = K - i ; if ( greaterE . length >= set1 && lessE . length >= set2 ) { var step1 = 0 ; var step2 = 0 ; for ( var j = 0 ; j < set1 ; j ++ ) step1 += greaterE [ j ] ; for ( var j = 0 ; j < set2 ; j ++ ) step2 += lessE [ j ] ; mi = Math . min ( mi , Math . max ( step1 , step2 ) ) ; } } document . write ( mi ) ; } var S = " " ; var N = S . length ; var K = 2 ; minOperation ( S , N , K ) ;