Sub topic 7
Trying Every Ordering with Permutations
Some problems ask you to choose an ordering of items rather than a group of them. Examples include the order in which to visit cities, the sequence in which to run jobs, and the arrangement of people at a table. Each candidate solution in these problems is a permutation, which is one specific ordering of all the items. Brute force means generating every permutation, scoring each one, and keeping the best.
This chapter assumes you can write recursive functions in Python and know basic Big-O notation. It also assumes you have read the earlier chapters on defining a search space and estimating brute-force cost. The chapter covers how to generate orderings with the standard library and by hand, how to shrink the space with symmetry, how to handle duplicate items, and the mistakes that most often break permutation code.
The Search Space of Orderings
With n distinct items, the first position has n choices, the second has n − 1, and so on down to one. The number of orderings is therefore n! (n factorial). The candidate solution is the full sequence, and the brute force evaluates a cost or validity check on each sequence.
Factorial growth is much steeper than the 2^n growth of subset enumeration. The table below shows when an exhaustive search over orderings stops being practical in Python, assuming each ordering costs roughly O(n) work to score and that Python handles about 10^7 simple operations per second.
| n | n! | Rough Python time to score all orderings |
|---|---|---|
| 5 | 120 | instant |
| 8 | 40,320 | instant |
| 10 | 3,628,800 | a few seconds |
| 11 | 39,916,800 | about a minute |
| 12 | 479,001,600 | many minutes |
| 15 | about 1.3 × 10^12 | infeasible |
In practice, a plain permutation brute force works up to about n = 10 in Python and n = 11 or 12 in C++. If the problem allows larger n, you need a different approach, but the brute force is still worth writing as a reference.
Generating Permutations with itertools
The standard library function itertools.permutations yields every ordering as a tuple. It is lazy, so it produces one tuple at a time and never holds all n! of them in memory.
import itertools
for p in itertools.permutations(["A", "B", "C"]):
print(p)This prints the six orderings in lexicographic order of input positions: ('A', 'B', 'C'), ('A', 'C', 'B'), ('B', 'A', 'C'), and so on. Two details matter:
- The ordering is by input position, not by value. If the input is not sorted, the output is not sorted by value either.
- Items are treated as distinct by position.
permutations([1, 1, 2])yields six tuples, and some of them are identical. This is covered in the section on duplicates.
itertools.permutations(items, k) yields ordered selections of length k, and there are n! / (n − k)! of them. Use it when you are choosing and ordering only some of the items, such as assigning gold, silver, and bronze among ten runners.
Writing Your Own Generator
Writing the generator yourself becomes necessary once you want to prune partial orderings, which a later chapter covers, or when you work in a language without a library helper. The standard recursive version builds the ordering one position at a time and tracks which items are already used.
def permutations_of(items):
n = len(items)
used = [False] * n
current = []
def build():
if len(current) == n:
yield tuple(current) # copy: current keeps changing
return
for i in range(n):
if not used[i]:
used[i] = True
current.append(items[i])
yield from build()
current.pop()
used[i] = False
yield from build()
print(list(permutations_of(["A", "B", "C"])))Each level of recursion fills one position. After a recursive call returns, the code undoes its choice by popping the item and clearing the used flag, so the next loop iteration starts from a clean state. The diagram shows the recursion tree for three items.
The tree has n! leaves. Counting internal nodes as well, the total number of nodes is about e · n!, so the overhead above the leaves is a small constant factor.
The Most Common Bug
If you write yield current instead of yield tuple(current), every result refers to the same list object. By the time the caller inspects the results, the backtracking has emptied that list, and you get n! references to []. The same bug shows up when people append current to a results list without copying it. Always yield or store a copy.
A Worked Example: The Traveling Salesman
The traveling salesman problem (TSP) gives a matrix dist where dist[a][b] is the cost of travelling from city a to city b. The goal is the cheapest tour that visits every city once and returns to the start.
A tour is a cycle, so the tours 0→1→2→0 and 1→2→0→1 are the same route written from different starting points. Fixing city 0 as the start removes these rotations and shrinks the search from n! to (n − 1)! orderings.
import itertools
import math
def shortest_tour(dist):
n = len(dist)
best = math.inf
for perm in itertools.permutations(range(1, n)):
route = (0,) + perm + (0,)
cost = sum(dist[a][b] for a, b in zip(route, route[1:]))
best = min(best, cost)
return bestAppending the final 0 adds the return leg. Forgetting it is the most frequent TSP bug, and it produces costs that are too low and look plausible.
In practice you usually want the route as well as its cost. The version below also handles the empty input, which the original does not. With n == 0, permutations(range(1, 0)) yields one empty tuple, the route becomes (0, 0), and dist[0] raises IndexError.
import itertools
import math
def shortest_tour_with_route(dist):
n = len(dist)
if n == 0:
return 0, ()
best_cost, best_route = math.inf, None
for perm in itertools.permutations(range(1, n)):
route = (0,) + perm + (0,)
cost = sum(dist[a][b] for a, b in zip(route, route[1:]))
if cost < best_cost:
best_cost, best_route = cost, route
return best_cost, best_route
dist = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0],
]
print(shortest_tour_with_route(dist)) # (80, (0, 1, 3, 2, 0))A one-city input gives route (0, 0) with cost dist[0][0], which is 0. Check that this matches what your problem statement expects.
Exploiting Reversal Symmetry
When the matrix is symmetric (dist[a][b] == dist[b][a]), a tour and its reverse cost the same. In the example, 0→1→3→2→0 and 0→2→3→1→0 both cost 80. You can skip half the orderings by keeping only those where perm[0] < perm[-1], which cuts the work to (n − 1)! / 2. Apply this only after you have confirmed that the matrix is symmetric. On an asymmetric instance, such as one-way streets, the reverse tour can cost a different amount, and the shortcut silently returns wrong answers.
Duplicate Items
If the items contain repeats, itertools.permutations generates identical orderings more than once. A multiset of n items, with counts c1, c2, and so on for each distinct value, has n! / (c1! · c2! · …) distinct orderings. For [1, 1, 2] that is 3! / 2! = 3, but the library yields 6 tuples.
There are two fixes:
- Wrap the generator in
set(...). This is correct, but it still generates every duplicate and stores all distinct results in memory. It is acceptable for small n. - Use the next-permutation algorithm. Starting from the sorted sequence, it steps to the next larger ordering in lexicographic order. It skips duplicates naturally because it compares values instead of positions.
def next_permutation(a):
"""Rearrange list a into the next lexicographic ordering in place.
Return False if a was already the last ordering."""
i = len(a) - 2
while i >= 0 and a[i] >= a[i + 1]:
i -= 1
if i < 0:
return False
j = len(a) - 1
while a[j] <= a[i]:
j -= 1
a[i], a[j] = a[j], a[i]
a[i + 1:] = reversed(a[i + 1:])
return True
a = sorted([2, 1, 1])
while True:
print(a)
if not next_permutation(a):
break
# [1, 1, 2]
# [1, 2, 1]
# [2, 1, 1]The algorithm finds the rightmost position i that can still be increased. It swaps a[i] with the smallest larger value to its right, then reverses the suffix after i so that the suffix is in its smallest order. Each step takes O(n) time in the worst case and O(1) time on average. The algorithm also uses O(1) extra memory, which makes it a good fit for languages where recursion depth or generator overhead is a concern. C++ provides it as std::next_permutation.
Common Errors Checklist
| Mistake | Symptom | Fix |
|---|---|---|
| Missing return leg in a cycle | Costs too low | Append the start city to the route |
| Yielding the mutable `current` list | All results empty or identical | Yield `tuple(current)` |
| Not undoing the choice after recursion | Missing orderings, `used` stays set | Pop and reset after every recursive call |
| Duplicates in input | Overcounted answers | Use `set` or next-permutation |
| Reversal shortcut on asymmetric costs | Wrong optimum | Check symmetry first |
| Materializing all permutations | Memory blowup | Iterate lazily |
| Starting next-permutation unsorted | Some orderings skipped | Sort before the loop |
Recognizing an Ordering Problem
Ask what changes between two candidate answers. If the answer changes when you swap two items, the problem is about order, and permutations are the right search space. If swapping never changes the answer and only membership matters, you are looking at subsets, and enumerating permutations wastes a factor of up to k! per subset of size k. Some problems mix the two. "Pick 3 of 10 tasks and decide their order" is a partial permutation, and permutations(items, 3) covers it directly with 720 candidates.
Exercise
A delivery driver starts and ends at a depot and must visit 9 customers. Costs are symmetric. How many orderings does the brute force check if you fix the depot as the start and also remove reversals? Is that feasible in Python?
Show answer
There are 10 locations including the depot. Fixing the depot leaves 9! = 362,880 orderings of the customers. Removing reversals halves that to 181,440. Each tour takes about 10 additions to score, which comes to roughly 2 million operations. That finishes in well under a second in Python.
Exercise
How many distinct orderings does the string "AABBB" have, and how many tuples does itertools.permutations("AABBB") yield?
Show answer
The string has 5!/(2!·3!) = 10 distinct orderings. itertools.permutations treats positions as distinct, so it yields 5! = 120 tuples, and each distinct ordering appears 12 times.
Exercise
A student's generator uses results.append(current) in the base case instead of results.append(tuple(current)). What does results contain after permuting [1, 2, 3], and why?
Show answer
It contains six references to the same list object. The backtracking pops every element before the function returns, so all six entries print as []. The fix is to store a copy, for example tuple(current) or current[:].
Exercise
You have n jobs with durations d[i], and you want the order that minimizes the sum of completion times. Write the brute-force check for one ordering perm, and state its total running time.
Show answer
Keep a running clock t = 0 and a total = 0. For each job i in perm, set t += d[i] and then total += t. Return total, and take the minimum over all permutations. The total running time is O(n · n!). The brute force is also a good oracle for checking the greedy rule of sorting jobs by ascending duration, which is optimal for this problem.