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
def minOperation ( S , N , K ) : NEW_LINE INDENT if N % K : NEW_LINE INDENT print ( " Not ▁ Possible " ) NEW_LINE return NEW_LINE DEDENT count = [ 0 ] * 26 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT count [ ord ( S [ i ] ) - 97 ] += 1 NEW_LINE DEDENT E = N // K NEW_LINE greaterE = [ ] NEW_LINE lessE = [ ] NEW_LINE for i in range ( 0 , 26 ) : NEW_LINE INDENT if count [ i ] < E : NEW_LINE INDENT lessE . append ( E - count [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT greaterE . append ( count [ i ] - E ) NEW_LINE DEDENT DEDENT greaterE . sort ( ) NEW_LINE lessE . sort ( ) NEW_LINE mi = float ( ' inf ' ) NEW_LINE for i in range ( 0 , K + 1 ) : NEW_LINE INDENT set1 , set2 = i , K - i NEW_LINE if ( len ( greaterE ) >= set1 and len ( lessE ) >= set2 ) : NEW_LINE INDENT step1 , step2 = 0 , 0 NEW_LINE for j in range ( 0 , set1 ) : NEW_LINE INDENT step1 += greaterE [ j ] NEW_LINE DEDENT for j in range ( 0 , set2 ) : NEW_LINE INDENT step2 += lessE [ j ] NEW_LINE DEDENT mi = min ( mi , max ( step1 , step2 ) ) NEW_LINE DEDENT DEDENT print ( mi ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " accb " NEW_LINE N = len ( S ) NEW_LINE K = 2 NEW_LINE minOperation ( S , N , K ) NEW_LINE DEDENT