Generate lexicographically smallest string of 0 , 1 and 2 with adjacent swaps allowed | Function to print the required string ; count number of 1 s ; To check if the all the 1 s have been used or not ; Print all the 1 s if any 2 is encountered ; If str [ i ] = 0 or str [ i ] = 2 ; If 1 s are not printed yet ; Driver code
function printString ( str , n ) { let ones = 0 ; for ( let i = 0 ; i < n ; i ++ ) if ( str [ i ] == ' ' ) ones ++ ; let used = false ; for ( let i = 0 ; i < n ; i ++ ) { if ( str [ i ] == ' ' && ! used ) { used = true ; for ( let j = 0 ; j < ones ; j ++ ) document . write ( " " ) ; } if ( str [ i ] != ' ' ) document . write ( str [ i ] ) ; } if ( ! used ) for ( let j = 0 ; j < ones ; j ++ ) document . write ( " " ) ; } let str = " " ; let n = str . length ; printString ( str . split ( ' ' ) , n ) ;