Lexicographically smallest permutation with no digits at Original Index | 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
function smallestPermute ( n ) { var res = Array ( n + 1 ) . fill ( 0 ) ; if ( n % 2 == 0 ) { for ( var i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) res [ i ] = 48 + i + 2 ; else res [ i ] = 48 + i ; } } else { for ( var 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 ; } for ( var i = 0 ; i < res . length ; i ++ ) { res [ i ] = String . fromCharCode ( res [ i ] ) ; } return res . join ( " " ) ; } var n = 7 ; document . write ( smallestPermute ( n ) ) ;