LeetCode 60. Permutation Sequence
Question
The set [1, 2, 3, ..., n]
contains a total of n!
unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for n = 3
:
"123"
"132"
"213"
"231"
"312"
"321"
Given n
and k
, return the kth
permutation sequence.
Example 1:
1 | Input: n = 3, k = 3 |
Example 2:
1 | Input: n = 4, k = 9 |
Example 3:
1 | Input: n = 3, k = 1 |
Constraints:
1 <= n <= 9
1 <= k <= n!
Source: https://leetcode.com/problems/permutation-sequence/
Solution
We find the result digit by digit. For each digit, we can determine its value by dividing k
by the number of permutations of its suffix. By subtracting the number of skipped permutations from k
, we keep narrowing k
till we find a certain permutation.
Note that in each loop we need to removed current digit because we cannot reuse numbers. Also, permutations are in a lexicographic order, so we should keep nums
sorted. Remove operations do not break the order of nums
.
1 | // Time Complexity, O(n) |
LeetCode 60. Permutation Sequence
http://yenotes.org/2022/03/06/LeetCode-60-Permutation-Sequence/