Sub topic 6
Generating All Permutations
A permutation is an ordering of every element of a collection. The list [1, 2, 3] has six: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], and [3, 2, 1]. This chapter builds a permutation generator with the choose, explore, unchoose template and compares it with the subset generator from the previous chapter. It also shows a second technique that swaps elements in place.
This chapter assumes you can read recursive Python and know the template's three steps. It also assumes you know why results are stored as copies (path[:]) and not as references to the shared path list. Earlier chapters covered both.
How Permutations Differ From Subsets
The subset generator passes a start index so that each call looks only at later elements. That rule fits subsets because order does not matter there: [1, 2] and [2, 1] are the same subset, so the generator must not produce both.
Order is the whole point of a permutation. After picking 2 first, the generator must still be able to pick 1 next. The start index cannot express "any element not yet used", so we need a different way to track which elements are free.
The two problems also record results at different places in the tree:
| Aspect | Subsets | Permutations |
|---|---|---|
| Does order matter? | No | Yes |
| Which elements a node may choose | Only those after `start` | Any element not yet used |
| Where results are recorded | At every node | Only at leaves (full length) |
| Number of results for n distinct items | 2^n | n! |
| Extra state needed | The `start` index | A `used` array (or in-place swaps) |
The State-Space Tree
Every level of the tree fixes one more position. The root is the empty arrangement. It has n children, one for each element that could go first. Each of those has n − 1 children, and so on until every element is placed. The leaves are the permutations.
The branching factor shrinks by one at each level. The tree for [1, 2, 3] therefore has 1 + 3 + 6 + 6 = 16 nodes. In general, level k holds n!/(n − k)! nodes. The total is dominated by the last two levels, which together hold 2·n! nodes.
The `used`-Array Approach
A boolean list used has one entry per input position. used[i] is True while nums[i] is in the current path. At each node, the loop tries every index, skips the used ones, and applies the template to the rest.
def permutations(nums):
result = []
path = []
used = [False] * len(nums)
def backtrack():
if len(path) == len(nums):
result.append(path[:])
return
for i in range(len(nums)):
if used[i]:
continue
used[i] = True
path.append(nums[i])
backtrack()
path.pop()
used[i] = False
backtrack()
return result
print(permutations([1, 2, 3]))
# [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]This function has two pieces of mutable state, path and used, and both are restored after the recursive call. The choose step changes both. The unchoose step reverses both, in the opposite order. As a result, every node sees the state its parent had when it made the choice.
The loop always starts at index 0, so the output comes out in the input's order. If the input is sorted, the permutations come out in lexicographic order. Tests and callers sometimes depend on that.
Tracing the First Few Steps
- At the root,
i = 0is free. Mark it used and push1, sopath = [1]. - At depth 1, index 0 is skipped.
i = 1is free, sopath = [1, 2]. - At depth 2, only
i = 2is free, sopath = [1, 2, 3]. The length equals n, so the code records a copy and returns. - Back at depth 2, the code pops
3and clearsused[2]. The loop ends. - Back at depth 1, the code pops
2and clearsused[1]. Nowi = 2is free, sopath = [1, 3], and the next leaf is[1, 3, 2].
Step 5 shows why both resets matter. Index 1 must be free again before [1, 3, 2] can place 2 last.
A Common Bug: Forgetting to Clear `used`
If you remove used[i] = False, the code still runs without errors, but it returns the wrong answer.
def permutations_buggy(nums):
result, path = [], []
used = [False] * len(nums)
def backtrack():
if len(path) == len(nums):
result.append(path[:])
return
for i in range(len(nums)):
if used[i]:
continue
used[i] = True
path.append(nums[i])
backtrack()
path.pop()
# missing: used[i] = False
backtrack()
return result
print(permutations_buggy([1, 2, 3])) # [[1, 2, 3]]After the first leaf, every index stays marked as used. Every later loop skips every index, so the search finds nothing more. Whenever a backtracking function returns too few results, check first that every change made in the choose step is undone in the unchoose step.
The Swap Approach
A second technique needs no used array and no separate path. It splits the list in place: positions 0 to first - 1 are fixed, and positions first onward are the elements still available. To choose an element for position first, swap it into that position. To unchoose it, swap it back.
def permutations_swap(nums):
nums = list(nums) # work on a copy so the caller's list is untouched
result = []
def backtrack(first):
if first == len(nums):
result.append(nums[:])
return
for i in range(first, len(nums)):
nums[first], nums[i] = nums[i], nums[first] # choose
backtrack(first + 1) # explore
nums[first], nums[i] = nums[i], nums[first] # unchoose
backtrack(0)
return result
print(permutations_swap([1, 2, 3]))
# [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2]]Look at the last two results. The swap approach does not produce lexicographic order, even on sorted input. When it swaps 3 into position 0, it moves 1 to position 2. The suffix becomes [2, 1], which is no longer sorted.
| Criterion | `used` array | Swap in place |
|---|---|---|
| Extra memory besides the recursion stack | O(n) for `used` and `path` | None |
| Output order on sorted input | Lexicographic | Not lexicographic |
| Loop iterations per node | n (including skipped indices) | n − first (no skips) |
| Easy to extend with duplicate skipping | Yes, with sorted input | Harder, needs a per-level set |
| Easy to limit to length k | Change the base case | Change the base case and copy `nums[:k]` |
Use the used array by default. It is easier to read, its output order is predictable, and the duplicate-handling chapter builds on it. Use the swap approach when memory is tight or when you need to permute a buffer in place.
Edge Cases and Variations
- Empty input.
permutations([])returns[[]]. At the root,len(path) == 0 == len(nums), so the empty arrangement is recorded once. Mathematically this is correct, because 0! = 1. If your caller expects[]for empty input, handle that case before you call the function. - Partial permutations. To list ordered selections of k elements, change the base case to
len(path) == k. Everything else stays the same. The number of results is n!/(n − k)!. - Repeated values. On
[1, 1, 2], both functions return six lists, but only three are distinct. The code treats the two1s as different because they sit at different indices. The chapter "Avoiding Duplicate Results" fixes this without filtering duplicates out afterwards. - Large n. 10! is 3,628,800 and 12! is about 479 million. Storing every permutation quickly becomes infeasible. If you only need to look at each permutation once, turn the function into a generator that uses
yieldso the results are never all in memory at once.
Cost in Brief
There are n! leaves, and copying each one costs O(n), so the running time is at least O(n · n!). The internal nodes add only a constant factor, because the total node count is about e · n!. The recursion depth is n, so besides the output, the function needs O(n) space for the stack, path, and used. The chapter "Analyzing the Cost of Backtracking" derives these bounds carefully.
Exercise
Modify the used-array permutations function so it takes a second argument k and returns all ordered selections of exactly k elements. What does k_permutations([1, 2, 3], 2) return, and how many lists is that?
Show answer
Change the signature to def k_permutations(nums, k): and the base case to if len(path) == k:. Nothing else changes. The call returns [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]], which is 3!/(3 − 2)! = 6 lists.
Exercise
Suppose you delete path.pop() from the used-array version but keep used[i] = False. What goes wrong when you run it on [1, 2, 3]?
Show answer
path keeps growing because nothing is ever removed from it. After the first leaf, path is [1, 2, 3], and later appends make it longer, so len(path) == len(nums) is never true again. The result is [[1, 2, 3]] and nothing else, even though the search keeps running. Both pieces of state must be restored.
Exercise
How many nodes, including the root and the leaves, does the state-space tree have for permutations of 4 distinct elements? How many calls to backtrack does the used-array version make?
Show answer
Level k holds 4!/(4 − k)! nodes: 1 + 4 + 12 + 24 + 24 = 65. Each node is exactly one call to backtrack, so the function makes 65 calls.
Exercise
Rewrite permutations_swap as a generator that yields each permutation and never builds a result list. Why must it still yield a copy?
Show answer
Replace result.append(nums[:]) with yield nums[:], and replace the plain recursive call with yield from backtrack(first + 1). The outer function then does yield from backtrack(0). It must yield a copy because the swaps keep changing nums. If it yielded nums itself, a caller that saved the yielded lists would find that they are all the same object, and that object would hold whatever order the last swap left behind.