Permutations (LeetCode 46): Solution and Explanation

Medium
Array
Backtracking

Given an array of distinct integers, return every possible ordering of those integers. The orderings may be returned in any order.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

A permutation is built one position at a time. For the first slot you can pick any of the n numbers, for the second any of the remaining n - 1, and so on. That choice process naturally forms a tree: the root is an empty arrangement, each level fills one more slot, and each leaf is a complete permutation. There are n! leaves, and since the output itself has n! lists of length n, no algorithm can do better than O(n × n!).

Backtracking is the standard way to walk that tree without building it in memory. Keep a single list curr that holds the arrangement chosen so far. At each step, try every number that is not already in curr: append it, recurse to fill the next slot, then pop it off to restore curr before trying the next candidate. When curr has n elements, copy it into the results.

The pop after the recursive call is the essential move. It means every branch starts from exactly the state its parent saw, so one list is reused for the whole search. The reference solution tests membership with n not in curr, which is a linear scan, but because the input has at most six numbers that cost is negligible. For larger inputs you would track used elements with a boolean array or swap elements in place.

Approach: Backtracking with a shared path

  1. Create an empty result list res and define a recursive backtrack(curr).
  2. If len(curr) == len(nums), append a copy of curr to res and return.
  3. Otherwise loop over every n in nums and skip any value already in curr.
  4. For each unused value, append it to curr, call backtrack(curr) to fill the remaining positions, and then pop it to undo the choice.
  5. Start the search with backtrack([]) and return res.

Step-by-step example

nums = [1,2,3]
  1. From [], choose 1 to get [1]. From [1], choose 2 to get [1,2], then the only unused value 3 gives [1,2,3], which is recorded.
  2. Pop 3 and then 2. Back at [1], the next unused value is 3, giving [1,3], then 2 gives [1,3,2], which is recorded.
  3. Pop back to [] and choose 2. The same process yields [2,1,3] and [2,3,1].
  4. Choosing 3 first yields [3,1,2] and [3,2,1].
  5. The result holds all 6 = 3! permutations in the order they were found.

Code: Python, Java, C++

1class Solution:
2    def permute(self, nums: List[int]) -> List[List[int]]:
3        res = []
4        
5        def backtrack(curr):
6            if len(curr) == len(nums):
7                res.append(curr.copy())
8                return
9            
10            for n in nums:
11                if n not in curr:
12                    curr.append(n)
13                    backtrack(curr)
14                    curr.pop()
15                    
16        backtrack([])
17        return res

Time and space complexity

Time

O(n² × n!)

There are n! complete permutations and about e × n! nodes in the recursion tree. At each node the loop runs n times and each in check scans up to n elements, giving O(n² × n!). With a boolean used array it drops to O(n × n!), which matches the output size.

Space

O(n)

Apart from the output, the recursion is n levels deep and curr holds at most n values. The output itself takes O(n × n!).

Other approaches

In-place swapping (time O(n × n!), space O(n))

Fix one index at a time: for position i, swap each element from i onward into position i, recurse on i + 1, then swap back. It avoids the membership check and any extra used array.

Iterative insertion (time O(n × n!), space O(n × n!))

Start with [[]] and, for each number, insert it into every possible position of every existing permutation. It builds the answer level by level without recursion.

Common mistakes

  • Appending curr itself instead of curr.copy(). Every stored entry would point to the same list, which ends up empty after backtracking.
  • Forgetting to pop after the recursive call, which leaves stale values in curr and produces lists longer than n.
  • Using n not in curr when the input can contain duplicates. That check would skip valid uses of a repeated value; the duplicates variant needs counts or sorting.
  • Shadowing the outer variable name in other languages. In the reference, the loop variable n is a value, not the length.

Frequently asked questions

What is the time complexity of generating all permutations?

Any algorithm must output n! permutations of length n, so O(n × n!) is the floor. The reference solution adds a linear membership check per candidate, which makes it O(n² × n!), still trivial for n up to 6.

Why do we need to copy the current list before adding it?

Backtracking keeps modifying the same curr list. Without a copy, every saved result would be a reference to that one list and would change as the search continues.

How do you handle permutations with duplicate numbers?

Sort the input and track which indices are used. When two equal values sit next to each other, only use the second one if the first is already in the current path. That prevents generating the same ordering twice.