Difficulty: Hard
Topics: Math & Geometry, Backtracking, Combinatorics
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
Input: n = 3, k = 3
Output: "213"
Input: n = 4, k = 9
Output: "2314"
Input: n = 3, k = 1
Output: "123"
$1 \le n \le 9$ $1 \le k \le n!$
Instead of generating all
- The list of
$n!$ permutations is grouped into$n$ blocks of size$(n - 1)!$ , each starting with a different digit in${1, 2, \dots, n}$ . - By zero-indexing
$k \leftarrow k - 1$ :- The first digit is chosen at index
idx = k / (n - 1)!from the available sorted digits. - Append
numbers[idx]and remove it fromnumbers. - Update
$k \leftarrow k \bmod (n - 1)!$ .
- The first digit is chosen at index
- Repeat the process for
$(n - 2)!, (n - 3)!, \dots, 1!$ .
-
Time Complexity:
$\mathcal{O}(N^2)$ where$N \le 9$ ($N$ steps, with array deletion taking$\mathcal{O}(N) \implies \le 81$ operations, 0 ms in C++). -
Space Complexity:
$\mathcal{O}(N)$ auxiliary space for tracking available digits.
-
$N = 1$ : Handled immediately$\implies \text{"1"}$ . -
$k = 1$ (First permutation): Outputs"123...n". -
$k = n!$ (Last permutation): Correctly computes descending sequence.