Permutations
LeetCode 46 · Medium · solution, intuition & step-by-step walkthrough
Fix position start, swap each choice into it.
This is how I solved Permutations (LeetCode 46), a medium problem from the Permutations pattern. Below: the intuition, the approach step by step, my accepted Python code and the 2 versions I wrote on the way, animated test cases and a line-by-line debugger.
Intuition
A permutation picks every element exactly once, in some order. Either build it by appending unused numbers, or generate in place by swapping each candidate into the current position and recursing on the rest.
Approach
- 1
Version 1: append any number not yet in the list.
- 2
Version 2: for i from start, swap nums[i] into position start.
- 3
Recurse for start + 1, then swap back.
- 4
Record when start reaches n.
How I solved it · from first idea to final
Append unused numbers.
No extra used-array.
Build with membership checkPythonO(n²·n!) time
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res=[]
def dfs(index,ds):
if index == len(nums):
res.append(ds[:])
for num in nums:
if num not in ds:
ds.append(num)
dfs(index+1,ds)
ds.pop()
dfs(0,[])
return resSwap in placePythonO(n·n!) time
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res=[]
def dfs(start,ds):
if start == len(nums):
res.append(ds[:])
for i in range(start,len(nums)):
nums[i],nums[start]=nums[start],nums[i]
dfs(start+1,nums)
nums[start],nums[i]=nums[i],nums[start]
dfs(0,[])
return resPermutations — FAQ
What is the intuition behind Permutations?
A permutation picks every element exactly once, in some order. Either build it by appending unused numbers, or generate in place by swapping each candidate into the current position and recursing on the rest.
How do you solve Permutations (LeetCode 46)?
1. Version 1: append any number not yet in the list. 2. Version 2: for i from start, swap nums[i] into position start. 3. Recurse for start + 1, then swap back. 4. Record when start reaches n.
What is the time and space complexity of Permutations?
Time: O(n · n!). Space: O(n). (Accepted approach: Swap in place.)
What are common mistakes in Permutations?
`num not in ds` costs O(n) and breaks with duplicate values.
Is there more than one way to solve Permutations?
Build with membership check (O(n²·n!) time): Append unused numbers. Swap in place (O(n·n!) time): No extra used-array.