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 is 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 is more than n / 3 ; Increase the number of b 's from back  ; Check if it is ' a ' and it is 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
< ? php function lexoSmallest ( $ s , $ n ) { $ ca = 0 ; $ cb = 0 ; $ cc = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ s [ $ i ] == ' a ' ) $ ca ++ ; else if ( $ s [ $ i ] == ' b ' ) $ cb ++ ; else $ cc ++ ; } if ( $ ca == $ cb && $ cb == $ cc ) { return $ s ; } $ cnt = floor ( $ n / 3 ) ; if ( $ cnt * 3 != $ n ) { return " - 1" ; } $ i = 0 ; while ( $ ca < $ cnt && $ i < $ n ) { if ( $ s [ $ i ] == ' b ' && $ cb > $ cnt ) { $ cb -- ; $ s [ $ i ] = ' a ' ; $ ca ++ ; } else if ( $ s [ $ i ] == ' c ' && $ cc > $ cnt ) { $ cc -- ; $ s [ $ i ] = ' a ' ; $ ca ++ ; } $ i ++ ; } $ i = 0 ; while ( $ cb < $ cnt && $ i < $ n ) { if ( $ s [ $ i ] == ' c ' && $ cc > $ cnt ) { $ cc -- ; $ s [ $ i ] = '1' ; $ cb ++ ; } $ i ++ ; } $ i = $ n - 1 ; while ( $ cc < $ cnt && $ i >= 0 ) { if ( $ s [ $ i ] == ' a ' && $ ca > $ cnt ) { $ ca -- ; $ s [ $ i ] = ' c ' ; $ cc ++ ; } $ i -- ; } $ i = $ n - 1 ; while ( $ cb < $ cnt && $ i >= 0 ) { if ( $ s [ $ i ] == ' a ' && $ ca > $ cnt ) { $ ca -- ; $ s [ $ i ] = ' b ' ; $ cb ++ ; } $ i -- ; } $ i = $ n - 1 ; while ( $ cc < $ cnt && $ i >= 0 ) { if ( $ s [ $ i ] == ' b ' && $ cb > $ cnt ) { $ cb -- ; $ s [ $ i ] = ' c ' ; $ cc ++ ; } $ i -- ; } return $ s ; } $ s = " aaaaaa " ; $ n = strlen ( $ s ) ; echo lexoSmallest ( $ s , $ n ) ; ? >