Minimize the number of replacements to get a string with same number of ' a ' , ' b ' and ' c ' in it | Function to count numbers ; Count the number of ' a ' , ' b ' and ' c ' in string ; If equal previously ; If not a multiple of 3 ; Increase the number of a ' s ▁ by ▁ ▁ removing ▁ extra ▁ ' b ' and c ; Check if it is ' b ' and it more than n / 3 ; Check if it is ' c ' and it more than n / 3 ; Increase the number of b ' s ▁ by ▁ ▁ removing ▁ extra ▁ ' c ; Check if it is ' c ' and it more than n / 3 ; Increase the number of c 's from back ; Check if it is ' a ' and it more than n / 3 ; Increase the number of b 's from back ; Check if it is ' a ' and it more than n / 3 ; Increase the number of c 's from back ; Check if it is ' b ' and it more than n / 3 ; Driver Code
def lexoSmallest ( s , n ) : NEW_LINE INDENT ca = 0 NEW_LINE cb = 0 NEW_LINE cc = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == ' a ' ) : NEW_LINE INDENT ca += 1 NEW_LINE DEDENT elif ( s [ i ] == ' b ' ) : NEW_LINE INDENT cb += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cc += 1 NEW_LINE DEDENT DEDENT if ( ca == cb and cb == cc ) : NEW_LINE INDENT return s NEW_LINE DEDENT cnt = n // 3 NEW_LINE if ( cnt * 3 != n ) : NEW_LINE INDENT return " - 1" NEW_LINE DEDENT i = 0 NEW_LINE while ( ca < cnt and i < n ) : NEW_LINE INDENT if ( s [ i ] == ' b ' and cb > cnt ) : NEW_LINE INDENT cb -= 1 NEW_LINE s [ i ] = ' a ' NEW_LINE ca += 1 NEW_LINE DEDENT elif ( s [ i ] == ' c ' and cc > cnt ) : NEW_LINE INDENT cc -= 1 NEW_LINE s [ i ] = ' a ' NEW_LINE ca += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT i = 0 NEW_LINE DEDENT ' NEW_LINE INDENT while ( cb < cnt and i < n ) : NEW_LINE INDENT if ( s [ i ] == ' c ' and cc > cnt ) : NEW_LINE INDENT cc -= 1 NEW_LINE s [ i ] = '1' NEW_LINE cb += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT i = n - 1 NEW_LINE while ( cc < cnt and i >= 0 ) : NEW_LINE INDENT if ( s [ i ] == ' a ' and ca > cnt ) : NEW_LINE INDENT ca -= 1 NEW_LINE s [ i ] = ' c ' NEW_LINE cc += 1 NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT i = n - 1 NEW_LINE while ( cb < cnt and i >= 0 ) : NEW_LINE INDENT if ( s [ i ] == ' a ' and ca > cnt ) : NEW_LINE INDENT ca -= 1 NEW_LINE s [ i ] = ' b ' NEW_LINE cb += 1 NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT i = n - 1 NEW_LINE while ( cc < cnt and i >= 0 ) : NEW_LINE INDENT if ( s [ i ] == ' b ' and cb > cnt ) : NEW_LINE INDENT cb -= 1 NEW_LINE s [ i ] = ' c ' NEW_LINE cc += 1 NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT return s NEW_LINE DEDENT s = " aaaaaa " NEW_LINE n = len ( s ) NEW_LINE print ( * lexoSmallest ( list ( s ) , n ) , sep = " " ) NEW_LINE