Permutation Sequence

The set [1, 2, 3, ..., n] has n! distinct permutations. Listing them in lexicographic order and numbering them from 1 gives a sequence; for n = 3 it is "123", "132", "213", "231", "312", "321". Given n and k, return the kth permutation in this sequence.

30:00

Permutation Sequence
hard
Free written solution
Topics
Companies

The set [1, 2, 3, ..., n] has n! distinct permutations. Listing them in lexicographic order and numbering them from 1 gives a sequence; for n = 3 it is "123", "132", "213", "231", "312", "321". Given n and k, return the kth permutation in this sequence.

Example 1:
Input: {"n":3,"k":3}
Output: 213
Constraints:
  • 1≤n≤91 \leq n \leq 9

  • 1≤k≤n!1 \leq k \leq n!

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":3,"k":3}

There are 3! = 6 permutations of 1..3 in sorted order, and we want number 3. Start with a table of factorials: fact[0] = 1.

n = 3, k = 3 of 6

0-based rank: -

Block sizes: fact[j] = j!

0! = 1
1! = ?
2! = ?

Unused digits (index below)

built after the table

Answer so far

Variables
VariableValue
n3
k3
DepthFunction Call
Stack empty
0/17