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 INPUT Set [1, 2, 3, ..., n] 1 2 3 All 3! = 6 Permutations: 1: "123" 2: "132" 3: "213" 4: "231" 5: "312" 6: "321" Input Values: n = 3 k = 3 ALGORITHM STEPS 1 Initialize nums = [1,2,3], k = k-1 = 2 2 Find factorial groups (n-1)! = 2! = 2 perms/group 3 Select digit by index idx = k / (n-1)! = 2/2 = 1 4 Repeat for remaining k = k % (n-1)! = 0 Calculation Process: i=0: idx=2/2=1 --> pick "2" nums=[1,3], k=0 i=1: idx=0/1=0 --> pick "1" nums=[3], k=0 i=2: idx=0/1=0 --> pick "3" FINAL RESULT Building the kth permutation: Step-by-step construction: 2 ? ? Step 1 2 1 ? Step 2 2 1 3 Done! OUTPUT: "213" OK - 3rd permutation found! Key Insight: Instead of generating all n! permutations, use factorials to directly compute each digit position. Each position divides permutations into (n-1)! groups. Index = k / (n-1)! tells which digit to pick. Time: O(n^2) | Space: O(n) - Optimal without generating all permutations! TutorialsPoint - Permutation Sequence | Optimal Solution
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