text: Permutation present at the middle of lexicographic ordering of permutations of at most length N made up integers up to K | Function that finds the middle the lexicographical smallest sequence ; If K is even ; First element is K / 2 ; Remaining elements of the sequence are all integer K ; Stores the sequence when K is odd ; Iterate over the range [ 0 , N / 2 ] ; Check if the sequence ends with in 1 or not ; Remove the sequence ending in 1 ; If it doesn 't end in 1 ; Decrement by 1 ; Insert K to the sequence till its size is N ; Prthe sequence stored in the vector ; Driver Code
code: def lexiMiddleSmallest ( K , N ) : NEW_LINE INDENT if ( K % 2 == 0 ) : NEW_LINE INDENT print ( K // 2 , end = " ▁ " ) NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT print ( K , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE return NEW_LINE DEDENT a = [ ( K + 1 ) // 2 ] * ( N ) NEW_LINE for i in range ( N // 2 ) : NEW_LINE INDENT if ( a [ - 1 ] == 1 ) : NEW_LINE INDENT del a [ - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT a [ - 1 ] -= 1 NEW_LINE while ( len ( a ) < N ) : NEW_LINE INDENT a . append ( K ) NEW_LINE DEDENT DEDENT DEDENT for i in a : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT K , N = 2 , 4 NEW_LINE lexiMiddleSmallest ( K , N ) NEW_LINE DEDENT