Permutation Sequence (LeetCode 60): Solution and Explanation
List every permutation of 1..n in sorted order and return the kth one. Instead of generating them, treat k as a number in the factorial number system and read off one digit per position.
Intuition
Generating permutations in order and stopping at the kth works, but there can be 9! = 362880 of them, and the counting is wasted work. The sorted list has a lot of structure to exploit.
Group the sorted permutations of 1..n by their first digit. Every digit leads the same number of permutations, (n - 1)!, and the groups appear in increasing order of that digit. So the first digit is decided by which group k lands in.
Once the first digit is fixed, the problem repeats on the n - 1 digits that are left, with k replaced by its position inside the group. Using a 0-based rank makes both parts one integer operation: the group is k // (n - 1)! and the position inside it is k % (n - 1)!.
Approach: Factorial number system
- Build
fact[j] = j!for j from 0 to n - 1. - Put the digits 1..n into a list in increasing order and subtract 1 from k so it is a 0-based rank.
- For i from n - 1 down to 0, set
idx = k // fact[i]. That is the block k falls in, so the next digit is the idx-th unused digit. - Set
k %= fact[i]to keep only the rank inside that block, then append the chosen digit to the answer and remove it from the list. - After n rounds every digit is used. Join them and return the string.
Step-by-step example
n = 3, k = 3
- fact = [1, 1, 2]. Unused digits are 1, 2, 3. k becomes 2 after switching to 0-based.
- i = 2: the 6 permutations form 3 blocks of 2 (starting with 1, 2 and 3). idx = 2 // 2 = 1, so the first digit is 2. k = 2 % 2 = 0. Unused: 1, 3.
- i = 1: the 2 permutations left form 2 blocks of 1. idx = 0 // 1 = 0, so the next digit is 1. k = 0. Unused: 3.
- i = 0: one block of 1. idx = 0, so the last digit is 3.
- The answer is "213", which is indeed the third of 123, 132, 213, 231, 312, 321.
Code: Python, Java, C++
1class Solution:
2 def getPermutation(self, n: int, k: int) -> str:
3 fact = [1] * n
4 for i in range(1, n):
5 fact[i] = fact[i - 1] * i
6 digits = [str(d) for d in range(1, n + 1)]
7 k -= 1
8 result = []
9 for i in range(n - 1, -1, -1):
10 idx = k // fact[i]
11 k %= fact[i]
12 result.append(digits.pop(idx))
13 return "".join(result)1class Solution {
2 public String getPermutation(int n, int k) {
3 int[] fact = new int[n];
4 fact[0] = 1;
5 for (int i = 1; i < n; i++) {
6 fact[i] = fact[i - 1] * i;
7 }
8 List<Integer> digits = new ArrayList<>();
9 for (int d = 1; d <= n; d++) digits.add(d);
10 k--;
11 StringBuilder sb = new StringBuilder();
12 for (int i = n - 1; i >= 0; i--) {
13 int idx = k / fact[i];
14 k %= fact[i];
15 sb.append(digits.remove(idx));
16 }
17 return sb.toString();
18 }
19}1class Solution {
2public:
3 string getPermutation(int n, int k) {
4 vector<int> fact(n, 1);
5 for (int i = 1; i < n; i++) {
6 fact[i] = fact[i - 1] * i;
7 }
8 string digits;
9 for (int d = 1; d <= n; d++) digits += char('0' + d);
10 k--;
11 string result;
12 for (int i = n - 1; i >= 0; i--) {
13 int idx = k / fact[i];
14 k %= fact[i];
15 result += digits[idx];
16 digits.erase(idx, 1);
17 }
18 return result;
19 }
20};Time and space complexity
O(n^2)
There are n rounds and each removes one item from a list of up to n digits. With n at most 9 this is tiny.
O(n)
The factorial table, the list of unused digits and the answer each hold n entries.
Other approaches
Call next permutation k - 1 times (time O(n * k), space O(n))
Start from 12...n and apply the next-permutation step k - 1 times. Each step is O(n), so the total is O(n * k), which reaches a few million operations at n = 9. It is easy to reason about but does far more work than needed.
Backtracking with a counter (time O(n! ) without pruning, space O(n))
Generate permutations in sorted order by depth-first search and stop at the kth leaf. It can prune whole subtrees by comparing the counter with the subtree size, and with that pruning it turns into the factorial method above.
Common mistakes
- Forgetting to convert k to 0-based. With a 1-based k, the last permutation of each block divides into the next block, so you pick the wrong digit.
- Indexing into 1..n directly instead of into the list of unused digits. After a digit is used, the remaining digits shift positions.
- Using fact[n] instead of fact[n - 1] for the first block size. The first digit splits n! permutations into n blocks of (n - 1)!.
- Expecting overflow. 9! = 362880 fits easily in a 32-bit integer.
Frequently asked questions
Why does every first digit lead exactly (n - 1)! permutations?
Fixing the first digit leaves n - 1 distinct digits for the remaining positions, and they can be arranged in (n - 1)! ways no matter which digit you fixed.
What is the factorial number system?
It writes a number as a sum d_i * i! with each d_i at most i. The digits d_i of the 0-based rank k are exactly the idx values this algorithm computes, so the rank and the permutation are two views of the same number.
Can the list removals be made faster?
Yes, a Fenwick tree or order-statistics tree finds and removes the idx-th unused digit in O(log n), giving O(n log n). For n at most 9 a plain list is simpler and just as fast.