Permutation present at the middle of lexicographic ordering of permutations of at most length N made up integers up to K | Java program for the above approach ; 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
import java . io . * ; import java . util . * ; class GFG { static void lexiMiddleSmallest ( int K , int N ) { if ( K % 2 == 0 ) { System . out . print ( K / 2 + " ▁ " ) ; for ( int i = 0 ; i < N - 1 ; ++ i ) { System . out . print ( K + " ▁ " ) ; } System . out . println ( ) ; return ; } ArrayList < Integer > a = new ArrayList < Integer > ( ) ; for ( int i = 0 ; i < N / 2 ; ++ i ) { if ( a . get ( a . size ( ) - 1 ) == 1 ) { a . remove ( a . size ( ) - 1 ) ; } else { int t = a . get ( a . size ( ) - 1 ) - 1 ; a . set ( a . get ( a . size ( ) - 1 ) , t ) ; while ( a . size ( ) < N ) { a . add ( K ) ; } } } for ( int i : a ) { System . out . print ( i + " ▁ " ) ; } System . out . println ( ) ; } public static void main ( String [ ] args ) { int K = 2 , N = 4 ; lexiMiddleSmallest ( K , N ) ; } }