Generate lexicographically smallest string of 0 , 1 and 2 with adjacent swaps allowed | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printString ( string str , int n ) { int ones = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( str [ i ] == '1' ) ones ++ ; bool used = false ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == '2' && ! used ) { used = 1 ; for ( int j = 0 ; j < ones ; j ++ ) cout << "1" ; } if ( str [ i ] != '1' ) cout << str [ i ] ; } if ( ! used ) for ( int j = 0 ; j < ones ; j ++ ) cout << "1" ; } int main ( ) { string str = "100210" ; int n = str . length ( ) ; printString ( str , n ) ; return 0 ; }