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 ; Print the sequence stored in the vector ; Driver Code
code: function lexiMiddleSmallest ( K , N ) { if ( K % 2 == 0 ) { document . write ( K / 2 + " " ) ; for ( let i = 0 ; i < N - 1 ; ++ i ) { document . write ( K + " " ) ; } document . write ( " " ) ; return ; } let a = [ ] ; for ( let i = 0 ; i < N / 2 ; ++ i ) { if ( a [ a . length - 1 ] == 1 ) { a . pop ( a . length - 1 ) ; } else { a [ a . length - 1 ] -= 1 ; while ( a . length < N ) { a . push ( K ) ; } } } for ( let i in a ) { document . write ( i + " " ) ; } document . write ( " " ) ; } let K = 2 , N = 4 ; lexiMiddleSmallest ( K , N ) ;