Lexicographically smallest permutation with no digits at Original Index | C ++ program to find the smallest permutation ; Function to print the smallest permutation ; when n is even ; when n is odd ; handling last 3 digit ; add EOL and print result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string smallestPermute ( int n ) { char res [ n + 1 ] ; if ( n % 2 == 0 ) { for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) res [ i ] = 48 + i + 2 ; else res [ i ] = 48 + i ; } } else { for ( int i = 0 ; i < n - 2 ; i ++ ) { if ( i % 2 == 0 ) res [ i ] = 48 + i + 2 ; else res [ i ] = 48 + i ; } res [ n - 1 ] = 48 + n - 2 ; res [ n - 2 ] = 48 + n ; res [ n - 3 ] = 48 + n - 1 ; } res [ n ] = ' \0' ; return res ; } int main ( ) { int n = 7 ; cout << smallestPermute ( n ) ; return 0 ; }