HardNo. 0060

Permutation Sequence — LeetCode 60 Python Solution

Topics
Recursion, Math
Reading time
3 min

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

PythonSolution
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

Time
O(n2)
Space · auxiliary
O(n)

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

Related problems
No.ProblemDifficulty
0050Pow(x, n)Medium
0002Add Two NumbersMedium
0273Integer to English WordsHard
0326Power of ThreeEasy
0390Elimination GameMedium
1808Maximize Number of Nice DivisorsHard

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(n2).

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.