Permutation Sequence
The problem
Given two integers n and k, return the k-th permutation sequence of the numbers [1, 2, 3, ..., n].
The permutations are arranged in lexicographic order (i.e., dictionary order).
You must solve the problem without generating all permutations explicitly.
Input: n = 3, k = 3 **Output: **"213" Explanation: The permutations in order are:
-
- 123
-
- 132
-
- 213 ← K = 3
-
- 231
-
- 312
-
- 321
**Input: **n = 3, k = 5 Output: "312" **Explanation: **K = 5 corresponds to the fifth permutation in lexicographic order.
Input: n = 4, k = 9
- 1 <= n <= 9
- 1 <= k <= n! (i.e., k is always a valid permutation index)
cpp
class Solution {
public:
string getPermutation(int n, int k) {
// Your code goes here
}
};java
class Solution {
public String getPermutation(int n, int k) {
// Your code goes here
}
}python
class Solution:
def getPermutation(self, n: int, k: int) -> str:
# Your code goes herejavascript
class Solution {
getPermutation(n, k) {
// Your code goes here
}
}csharp
class Solution {
public string GetPermutation(int n, int k) {
// Your code goes here
}
}go
func getPermutation(n int, k int) string {
// Your code goes here
}Stuck? Show a way to structure it+
- 01Convert one-based k to zero-based k minus one.
- 02Keep sorted unused digits and precompute factorials.
- 03At each remaining length m, choose index k divided by factorial(m minus one).
- 04Remove that digit and replace k with the remainder.
- 05Append until no digits remain.
Reference answer
Then expect these follow-ups
How would you find the rank of a given permutation?
Tests: follow-up reasoning
How does this change when digits can repeat?
Tests: constraint adaptation
Free to read · better with Enzo
Practice this out loud with Enzo
Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.
Next question