Generate lexicographically smallest string of 0 , 1 and 2 with adjacent swaps allowed | Java implementation of the approach ; 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
class GFG { static void printString ( char [ ] str , int n ) { int ones = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( str [ i ] == '1' ) ones ++ ; boolean used = false ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == '2' && ! used ) { used = true ; for ( int j = 0 ; j < ones ; j ++ ) System . out . print ( "1" ) ; } if ( str [ i ] != '1' ) System . out . print ( str [ i ] ) ; } if ( ! used ) for ( int j = 0 ; j < ones ; j ++ ) System . out . print ( "1" ) ; } public static void main ( String [ ] args ) { String str = "100210" ; int n = str . length ( ) ; printString ( str . toCharArray ( ) , n ) ; } }