You’re given two integers N and K, your task is to find the Kth permutation of the sequence of first N natural numbers.
For Example :
If N = 3 and K = 3.
The Possible Permutations for N = 3 are {(1,2,3), (1,3,2), (2,1,3), (2,3,1), (3,1,2), (3,2,1)}.
In this list, the 3rd Permutation sequence is 2 1 3.
The first line of the input contains an integer T denoting the number of test cases. The 'T' test cases follow.
The first line of each test case contains two space-separated integers N and K, as specified in the problem statement.
Output Format :
For each test case, print an array denoting the Kth permutation of the sequence of first N natural numbers.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 5 * 10^3
1 <= K <= min(N!, 5 * 10^3)
Time limit: 1 sec
2
2 2
2 1
2 1
1 2
Permutation sequences for N = 2 are {1 2,2 1}. The second term in this sequence list is {2 1}, which is the answer to the first test case, and the first term in this sequence list is {1 2}, which is the answer to the second test case.
2
3 6
3 3
3 2 1
2 1 3
Permutation sequences for N = 3 are {1 2 3,1 3 2,2 1 3,2 3 1,3 1 2,3 2 1}. The sixth term in this sequence list is {3 2 1}, which is the answer to the first test case and the third term in this sequence list is {2 1 3}, which is the answer to the second test case.
Generate all possible permutations of the sequence.
O(N*N!), where N is the number whose Kth permutation sequence is to be found.
In total there are N! Permutations possible, and in each call, we iterate on the number, and there are N such numbers, which will cost us O(N) time. Hence, to generate all the permutations we’ll take O(N*N!) time.
O(N*N!), where N is the number whose Kth permutation sequence is to be found.
As we are using a 2 Dimensional array with N! Columns and each column will have N rows to store the N! Possible permutations. Thus, the space complexity will be O(N*N!).