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
< ? php function printString ( $ str , $ n ) { $ ones = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) if ( $ str [ $ i ] == '1' ) $ ones ++ ; $ used = false ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ str [ $ i ] == '2' && ! $ used ) { $ used = 1 ; for ( $ j = 0 ; $ j < $ ones ; $ j ++ ) echo "1" ; } if ( $ str [ $ i ] != '1' ) echo $ str [ $ i ] ; } if ( ! $ used ) for ( $ j = 0 ; $ j < $ ones ; $ j ++ ) echo "1" ; } $ str = "100210" ; $ n = strlen ( $ str ) ; printString ( $ str , $ n ) ; ? >