DSA Factory
Free Backtracking lessonsBacktracking · Stage 2 · Permutations · Step 4

Jump straight to the kth ordering

Find the kth ordering of the numbers 1 to n in dictionary order without listing the ones before it, by counting how many orderings start with each choice. About 16 minutes.

Blocks of equal size

List the orderings of 1, 2, 3 in dictionary order: 123, 132, 213, 231, 312, 321. Those starting with 1 come first, then those starting with 2, then 3. Each block has the same size: two, which is 2 factorial.

For n digits, each block has (n − 1) factorial orderings. So to find the kth ordering, work out which block it is in.

Block size: (n − 1) factorial for the first digit.
Which block: k, counted from 0, divided by the block size.
In code
fact = [1, 1, 2, 6]
block = fact[2]     # 2 per first digit
idx = 3 // block    # 1
The 3rd ordering of 1, 2, 3, in dictionary order. Blocks have 2 orderings.
1
0
2
1
3
2
pick

k is 3, so position 2. Block size 2: position 2 divided by 2 is 1, so the second digit, 2, goes first.

Move 1 of 3

Repeat on what is left

The block number says which of the remaining digits goes first. Take it out of the list of digits and add it to the answer. The position of the wanted ordering inside its block is the remainder of the division.

Now repeat with one fewer digit, using the remainder as the new k. Counting from 0 matters: subtract 1 from k at the start, so that the first ordering has position 0.

Remainder: is the position inside the block.
Count from 0: subtract 1 from k first.
In code
k = k % block
digits.pop(idx)
Quick check

n is 4. How many orderings start with the digit 1?

  1. A6, which is 3 factorial
  2. B4
  3. C24
Show the answer

6, which is 3 factorial. The remaining three digits can be ordered in 3 factorial ways.

Your problem

Permutation sequence

The numbers 1 to n have n! orderings. Listed in dictionary order (as digit strings), the orderings of 1, 2, 3 are "123", "132", "213", "231", "312" and "321". Given n and k, return the kth ordering in this list, counting from k = 1, as a string of digits.

Example
n = 3, k = 3 → "213"

1 ≤ n ≤ 9 · 1 ≤ k ≤ n!

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve