Permutations — LeetCode 46 Python Solution

MediumArrayBacktracking
Problem
#46
Reading time
3 min

The problem

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

Example

Input
nums = [1,2,3]
Output
[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

Python solution

Python
class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        def dfs(i: int):
            if i >= n:
                ans.append(t[:])
                return
            for j, x in enumerate(nums):
                if not vis[j]:
                    vis[j] = True
                    t[i] = x
                    dfs(i + 1)
                    vis[j] = False

        n = len(nums)
        vis = [False] * n
        t = [0] * n
        ans = []
        dfs(0)
        return ans

Complexity

MeasureComplexity
TimeO(n \times n!), where n is the length of the array
SpaceO(depth) auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 46. Permutations is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

On study lists

This problem is on NeetCode 150, Grind 75 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 46. Permutations?
LeetCode 46. Permutations is rated Medium on LeetCode.
What is the time complexity of LeetCode 46. Permutations?
The Python solution on this page runs in O(n \times n!), where n is the length of the array.
What is the space complexity of LeetCode 46. Permutations?
The Python solution on this page uses O(depth) auxiliary space.
What topics does LeetCode 46. Permutations cover?
LeetCode 46. Permutations is tagged Array and Backtracking 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.

Get Stealth Interview