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 Str1 [ i ] = 0 or Str1 [ i ] = 2 ; If 1 s are not printed yet ; Driver code
def printString ( Str1 , n ) : NEW_LINE INDENT ones = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( Str1 [ i ] == '1' ) : NEW_LINE INDENT ones += 1 NEW_LINE DEDENT DEDENT used = False NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( Str1 [ i ] == '2' and used == False ) : NEW_LINE INDENT used = 1 NEW_LINE for j in range ( ones ) : NEW_LINE INDENT print ( "1" , end = " " ) NEW_LINE DEDENT DEDENT if ( Str1 [ i ] != '1' ) : NEW_LINE INDENT print ( Str1 [ i ] , end = " " ) NEW_LINE DEDENT DEDENT if ( used == False ) : NEW_LINE INDENT for j in range ( ones ) : NEW_LINE INDENT print ( "1" , end = " " ) NEW_LINE DEDENT DEDENT DEDENT Str1 = "100210" NEW_LINE n = len ( Str1 ) NEW_LINE printString ( Str1 , n ) NEW_LINE