Permutation Sequence — LeetCode 60 Python Solution
HardRecursionMath
- Problem
- #60
- Pattern
- Math and Number Theory
- Reading time
- 3 min
- Source
- leetcode.com
The problem
The set [1, 2, 3, ..., n] contains a total of n! unique permutations.
Example
- Input
- n = 3, k = 3
- Output
- "213"
Python solution
Python
class Solution:
def getPermutation(self, n: int, k: int) -> str:
ans = []
vis = [False] * (n + 1)
for i in range(n):
fact = 1
for j in range(1, n - i):
fact *= j
for j in range(1, n + 1):
if not vis[j]:
if k > fact:
k -= fact
else:
ans.append(str(j))
vis[j] = True
break
return ''.join(ans)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(n) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 60. Permutation Sequence is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 60. Permutation Sequence?
- LeetCode 60. Permutation Sequence is rated Hard on LeetCode.
- What is the time complexity of LeetCode 60. Permutation Sequence?
- The Python solution on this page runs in O(n^2).
- What is the space complexity of LeetCode 60. Permutation Sequence?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 60. Permutation Sequence cover?
- LeetCode 60. Permutation Sequence is tagged Recursion and Math on LeetCode.