/60. Permutation Sequence

60. Permutation Sequence

Hard
Probability52.3% acceptance

Given two integers total_elements and sequence_index, where total_elements represents the size of the set {1, 2, ..., total_elements}, and sequence_index represents the 1-based index, return the sequence_index-th permutation of the set in lexicographical order as a string.

Example 1

Input: total_elements=5, sequence_index=16

Output: 32541

Explanation: The 16th permutation of [1,2,3,4,5] in lexicographical order is 32541.

Example 2

Input: total_elements=2, sequence_index=2

Output: 21

Explanation: The 2nd permutation of [1,2] is 21.

Example 3

Input: total_elements=4, sequence_index=7

Output: 1432

Explanation: The 7th permutation of [1,2,3,4] is 1432.

Constraints

  • 1 <= total_elements <= 9
  • 1 <= sequence_index <= factorial(total_elements)
Python (current runtime)

Case 1

Input: total_elements=3, sequence_index=5

Expected: 312

Case 2

Input: total_elements=4, sequence_index=12

Expected: 2431

Case 3

Input: total_elements=6, sequence_index=20

Expected: 146325