![]() |
VOOZH | about |
Given two integers n and k, find the k-th permutation sequence of the first n natural numbers arranged in lexicographical order. Return the answer as a string.
Examples:
Input: n = 4, k = 3
Output: 1324
Explanation: The permutations in lexicographical order are 1234, 1243, 1324, ..., so the 3rd permutation is 1324.Input: n = 3, k = 5
Output: 312
Explanation: The permutations in lexicographical order are 123, 132, 213, 231, 312, 321, so the 5th permutation is 312.
Table of Content
The idea is to generate all possible permutations of numbers. Store all permutations in a list, sort them lexicographically and return the k-th permutation.
312
The idea is based on the observation that in all permutations of n numbers, each number appears in the first position exactly (n - 1)! times. Hence, the first digit of the k-th permutation can be directly determined using: index = k / (n - 1)!.
Once the digit is selected, it is removed from the list of available digits since it cannot be reused. The problem then reduces to finding the permutation of the remaining n - 1 digits.
Next, update k as k = k % (n - 1)! to focus only on the remaining block of permutations. This process is repeated for each position until all digits are selected.
Consider n = 3 and k = 5, initially available numbers are [1, 2, 3], after converting k into 0- based indexing k = 4, and the factorial values are 0! = 1, 1! = 1, and 2! = 2.
Step 1: Find the First Digit
Step 2: Find the Second Digit
Step 3: Find the Last Digit
Final answer becomes: "312"
312