Permutation Sequence

Hard Recursion AI round

The digits 1 to n can be written in n! different orders, each a string of n digits that uses every digit once.

List those strings from smallest to largest and number them from 1: the first has its digits in increasing order, and the last in decreasing order.

Given n and k, return the string at place k of that list.

Example 1

Input: n = 3, k = 5
Output: "312"

The six orders of 1, 2 and 3, from smallest to largest, are 123, 132, 213, 231, 312 and 321. The fifth is 312.

Example 2

Input: n = 4, k = 17
Output: "3412"

Each first digit begins 6 of the 24 orders, so places 13 to 18 begin with 3: 3124, 3142, 3214, 3241, 3412 and 3421. Place 17 is the fifth of them.

Example 3

Input: n = 6, k = 500
Output: "516243"

Constraints

  • 1 ≤ n ≤ 9
  • 1 ≤ k ≤ n!, the number of orders (9! is 362,880)

More Recursion

All Recursion problems