Permutation Sequence - Problem

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 kth permutation sequence.

Input & Output

Example 1 — Small Case
$ Input: n = 3, k = 3
Output: "213"
💡 Note: All permutations in order: ["123", "132", "213", "231", "312", "321"]. The 3rd permutation is "213".
Example 2 — First Permutation
$ Input: n = 4, k = 1
Output: "1234"
💡 Note: The first permutation in lexicographical order is always the numbers in ascending order: "1234".
Example 3 — Last Permutation
$ Input: n = 3, k = 6
Output: "321"
💡 Note: For n=3, there are 3!=6 permutations total. The 6th (last) permutation is "321" (descending order).

Constraints

  • 1 ≤ n ≤ 9
  • 1 ≤ k ≤ n!

Visualization

Tap to expand
Permutation Sequence: Find kth Permutation EfficientlyInput: n = 3, k = 3Find 3rd permutation of [1, 2, 3]Naive Way:Generate all 6permutations:123,132,213,231,312,321Smart Way:Use factorial mathk÷(n-1)! = positionDirect calculationStep-by-step calculation:Position 0: (3-1)÷2! = 1 → pick "2"Position 1: 0÷1! = 0 → pick "1"Position 2: remaining → pick "3"Result: "213"Time: O(n²) vs O(n! × n) brute force
Understanding the Visualization
1
Input
Given n=3, k=3, find 3rd permutation of [1,2,3]
2
Process
Use factorial arithmetic to calculate position of each digit
3
Output
Direct result: "213" without generating all 6 permutations
Key Takeaway
🎯 Key Insight: Use factorial number system to calculate digit positions directly without generating all permutations
Asked in
Google 15 Facebook 12 Microsoft 8 Amazon 6
125.0K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen