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
def smallestPermute ( n ) : NEW_LINE INDENT res = [ " " ] * ( n + 1 ) NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT res [ i ] = chr ( 48 + i + 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT res [ i ] = chr ( 48 + i ) NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT for i in range ( n - 2 ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT res [ i ] = chr ( 48 + i + 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT res [ i ] = chr ( 48 + i ) NEW_LINE DEDENT DEDENT res [ n - 1 ] = chr ( 48 + n - 2 ) NEW_LINE res [ n - 2 ] = chr ( 48 + n ) NEW_LINE res [ n - 3 ] = chr ( 48 + n - 1 ) NEW_LINE DEDENT res = ' ' . join ( res ) NEW_LINE return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 7 NEW_LINE print ( smallestPermute ( n ) ) NEW_LINE DEDENT