Form lexicographically smallest string with minimum replacements having equal number of 0 s , 1 s and 2 s | Function that returns the modified lexicographically smallest String after performing minimum number of given operations ; Stores the initial frequencies of characters 0 s , 1 s and 2 s ; Stores number of processed characters upto that point of each type ; Required number of characters of each type ; If the current type has already reqd number of characters , no need to perform any operation ; Process all 3 cases ; Check for 1 first ; Else 2 ; Here we need to check processed [ 1 ] only for 2 since 0 is less than 1 and we can replace it anytime ; Here we can replace 2 with 0 and 1 anytime ; keep count of processed characters of each type ; Driver Code
function formStringMinOperations ( s ) { var count = new Array ( 3 ) . fill ( 0 ) ; for ( const c of s ) { count += 1 ; } var processed = new Array ( 3 ) . fill ( 0 ) ; var reqd = parseInt ( s . length / 3 ) ; for ( var i = 0 ; i < s . length ; i ++ ) { if ( count [ s [ i ] . charCodeAt ( 0 ) - " " . charCodeAt ( 0 ) ] === reqd ) { continue ; } if ( s [ i ] === " " && count [ 0 ] > reqd && processed [ 0 ] >= reqd ) { if ( count [ 1 ] < reqd ) { s [ i ] = " " ; count [ 1 ] ++ ; count [ 0 ] -- ; } else if ( count [ 2 ] < reqd ) { s [ i ] = " " ; count [ 2 ] ++ ; count [ 0 ] -- ; } } if ( s [ i ] === " " && count [ 1 ] > reqd ) { if ( count [ 0 ] < reqd ) { s [ i ] = " " ; count [ 0 ] ++ ; count [ 1 ] -- ; } else if ( count [ 2 ] < reqd && processed [ 1 ] >= reqd ) { s [ i ] = " " ; count [ 2 ] ++ ; count [ 1 ] -- ; } } if ( s [ i ] === " " && count [ 2 ] > reqd ) { if ( count [ 0 ] < reqd ) { s [ i ] = " " ; count [ 0 ] ++ ; count [ 2 ] -- ; } else if ( count [ 1 ] < reqd ) { s [ i ] = " " ; count [ 1 ] ++ ; count [ 2 ] -- ; } } processed [ s [ i ] . charCodeAt ( 0 ) - " " . charCodeAt ( 0 ) ] ++ ; } return s . join ( " " ) ; } var s = " " ; document . write ( formStringMinOperations ( s . split ( " " ) ) ) ;