Permutation Sequence Problem
Description
LeetCode Problem 60.
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:
Input: n = 3, k = 3
Output: "213"
Example 2:
Input: n = 4, k = 9
Output: "2314"
Example 3:
Input: n = 3, k = 1
Output: "123"
Constraints:
- 1 <= n <= 9
- 1 <= k <= n!
Solution
Approach: Pick One Digit at a Time with Factorials
Listing permutations one by one until the kth takes up to n! steps. Instead, we can work out each digit directly.
The permutations in order come in blocks: the first (n - 1)! all start with the smallest digit, the next (n - 1)! start with the second smallest, and so on. So the first digit is the one at index (k - 1) / (n - 1)! among the unused digits. Inside that block, the same reasoning applies to the remaining n - 1 digits, with the position inside the block, (k - 1) % (n - 1)!.
Steps:
- Precompute
factorial[0..n]and keep the unused digits1..nin increasing order. - Set
k = k - 1so the rank starts at 0 (this is the usual off-by-one). - For
remaining = ndown to 1: letblock = factorial[remaining - 1]. Take and remove the unused digit at indexk / block, then setk = k % block.
Example, n = 4, k = 9: the rank is 8. 8 / 3! = 1, so the first digit is 2 and the rank becomes 2. With {1, 3, 4} left: 2 / 2! = 1 gives 3, rank 0. Then 1, then 4: "2314".
Complexity: O(n2) time, because removing a digit from the list takes O(n), and O(n) space.
class Solution:
def getPermutation(self, n: int, k: int) -> str:
factorial = [1] * (n + 1)
for i in range(1, n + 1):
factorial[i] = factorial[i - 1] * i
digits = [str(d) for d in range(1, n + 1)] # digits not used yet, in increasing order
k -= 1 # 0-based rank among the permutations
result = []
for remaining in range(n, 0, -1):
block = factorial[remaining - 1] # permutations that start with each unused digit
index = k // block
result.append(digits.pop(index))
k %= block
return "".join(result)
Now write it from memory
Close the write-up and solve it yourself against the tests.