
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.
For each test case, print an array denoting the Kth permutation of the sequence of first N natural numbers.
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
Let’s see how will we calculate the indices:
The starting position of any N length sequence is occupied by each of the numbers from 1 to n exactly n! / n that is (n-1)! times and that too in an Increasing order. So the first position of the kth sequence will be occupied by the number present at index = (k-1) / (n-1)!. We are using K-1 instead of K because we are using 0-Based Indexing. Similarly, we’ll do this for the other indices.
As we know calculating factorials can be very tedious work. Hence we use an observation here that, as soon as the product of the n*(n-1)*(n-1).... > K, we do not need to calculate the actual factorial value. The reason for this is that K/(nOriginal) and K/(nPartial) both will become equal to 0, when nPartial > K, where nOriginal is the original factorial value of N and nPartial is the partial factorial value of N. Hence we can save our time here by not calculating the factorial values.
Let’s understand the above steps with the help of an example: