Leetcode #46: Permutations
In this guide, we solve Leetcode #46 Permutations in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, Backtracking
Intuition
We must explore combinations of choices, but many branches can be pruned early.
Backtracking enumerates valid candidates while keeping the search space under control.
Approach
Use DFS to build candidates step by step, and backtrack when constraints are violated.
Pruning keeps the exploration practical for typical constraints.
Steps:
- Define the decision tree.
- DFS through choices and backtrack.
- Prune invalid paths early.
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
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
The time complexity is , where is the length of the array. The space complexity is O(depth).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.