O(n!) factorial time
easy 15 minO(n!) means the work grows like n × (n - 1) × ...
Video lesson · Chapter 1 of 6
Every speaker gets a distinct cue
O(n!) factorial time
1:24Reel
Read caption
Tali auditions the possible orders of distinct floats, reusing one lineup and scoring each last float. One fewer choice at every position.
How it works
Step through the idea, or press Play.
Pick the first item. Any of the n items can go first, so the search branches n ways
Understand it
Start here
What O(n!) means
An algorithm is O(n!) when its work grows like , the number of ways to put different items in order. It shows up whenever the algorithm tries every arrangement. It is the steepest growth rate you will meet in interviews, steeper even than exponential .
The factorial, defined recursively
Every ordering
Factorial time means visiting all orderings of the input, one by one.
The multiplier grows
doubles per item. multiplies by , so the 11th item multiplies the work by 11.
Tiny inputs only
million is fine; billion takes seconds; takes decades.
The picture
The permutation tree
Every ordering of [1, 2, 3]
The product rule
The math
Counting the real work
Generating all permutations visits every node of the tree, not only the leaves. There are nodes at depth , and adding them up gives a little under calls. Each leaf also copies an array of length into the result, so the true cost of listing every permutation is .
Calls in the recursion tree
The recurrence
Scale
How fast n! explodes
| n | At steps per second | |
|---|---|---|
| 5 | 120 | instant |
| 7 | 5,040 | instant |
| 10 | 3,628,800 | about 4 milliseconds |
| 12 | 479,001,600 | about half a second |
| 13 | 6,227,020,800 | about 6 seconds |
| 15 | about 1.3 trillion | about 22 minutes |
| 20 | about | about 77 years |
Stirling's approximation
A bonus: why sorting is n log n
Comparison
n! against 2ⁿ
| n | ||||
|---|---|---|---|---|
| 3 | 9 | 8 | 6 | 0.75 |
| 4 | 16 | 16 | 24 | 1.5 |
| 5 | 25 | 32 | 120 | 3.75 |
| 10 | 100 | 1,024 | 3,628,800 | about 3,544 |
| 15 | 225 | 32,768 | about 1.3 trillion | about 40 million |
| 20 | 400 | about 1 million | about | about 2.3 trillion |
Why the gap keeps widening
The growth ladder
Example 1
Generating permutations by swapping
One call of the swap backtracker
start is filled by each remaining item in turn. Swapping back restores the array so the next choice starts clean.def permute(arr): result = [] def backtrack(start): if start == len(arr): result.append(arr[:]) # copy, or every entry ends up the same list return for i in range(start, len(arr)): arr[start], arr[i] = arr[i], arr[start] # choose backtrack(start + 1) # explore arr[start], arr[i] = arr[i], arr[start] # undo backtrack(0) return resultperms = permute([1, 2, 3])print(perms) # [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2]]print(len(perms)) # 6 = 3!from itertools import permutationsprint(len(list(permutations("ABCDE")))) # 120 = 5!, still factorial workSwap in place
- Uses the input array itself, extra space for the recursion.
- Order is not lexicographic: 321 comes before 312.
- The usual interview answer for distinct items.
Build a path with a used[] array
- Keeps a separate path and a used flag per item.
- Produces lexicographic order if the input is sorted.
- Easier to extend to duplicates by skipping equal neighbours.
Example 2
Travelling salesman by brute force
A salesperson must visit cities once each and come home, by the shortest loop. The brute-force answer lists every order of the cities and keeps the cheapest. It does not need all orders, though: two kinds of duplicates can be removed.
Why there are (n-1)!/2 distinct tours
All (4 - 1)! = 6 routes from city 0
| Route | Legs | Total |
|---|---|---|
| 0 → 1 → 2 → 3 → 0 | 10 + 35 + 30 + 20 | 95 |
| 0 → 1 → 3 → 2 → 0 | 10 + 25 + 30 + 15 | 80 |
| 0 → 2 → 1 → 3 → 0 | 15 + 35 + 25 + 20 | 95 |
| 0 → 2 → 3 → 1 → 0 | 15 + 30 + 25 + 10 | 80 (reverse of row 2) |
| 0 → 3 → 1 → 2 → 0 | 20 + 25 + 35 + 15 | 95 (reverse of row 3) |
| 0 → 3 → 2 → 1 → 0 | 20 + 30 + 35 + 10 | 95 (reverse of row 1) |
from itertools import permutationsdef tsp_brute_force(dist): n = len(dist) best, best_route = float("inf"), None for perm in permutations(range(1, n)): # (n - 1)! orders route = (0,) + perm + (0,) d = sum(dist[route[k]][route[k + 1]] for k in range(n)) if d < best: best, best_route = d, route return best_route, bestdist = [ [0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0],]print(tsp_brute_force(dist)) # ((0, 1, 3, 2, 0), 80)Example 3
Next permutation in order
Sometimes you want to walk the permutations in dictionary order one at a time instead of storing them all. Next permutation turns one arrangement into the next in , so stepping through all of them costs time but only extra space. C++'s std::next_permutation works this way.
Next permutation in four moves
def next_permutation(arr): i = len(arr) - 2 while i >= 0 and arr[i] >= arr[i + 1]: i -= 1 # find the rightmost ascent if i < 0: return False # descending: this was the last order j = len(arr) - 1 while arr[j] <= arr[i]: j -= 1 # rightmost item bigger than arr[i] arr[i], arr[j] = arr[j], arr[i] arr[i + 1:] = reversed(arr[i + 1:]) return Truearr = [1, 2, 3]order = [arr[:]]while next_permutation(arr): order.append(arr[:])print(order) # [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]Relatives
Duplicates, derangements and pruning
Repeated items
With duplicates the count drops to . "AAB" has orders. Sort, then skip an item equal to its unused left neighbour.
Derangements
Orders where no item stays in its own place. About of them, so still factorial: , .
N-Queens
One queen per row, so the columns form a permutation. Pruning attacked squares cuts most of the tree, though the worst case stays exponential.
Counting derangements
Escape routes
What to do instead of n!
Choosing an approach for an ordering problem
| Problem | Brute force | Better |
|---|---|---|
| Travelling salesman | tours | Held-Karp DP : about 420 million steps at |
| Assign jobs to workers | matchings | Hungarian algorithm |
| Is one string an anagram of another? | rearrangements | Count letters |
| -th permutation in order | List of them | Factorial number system |
| Count arrangements | List them all | A formula: , , |
Pattern spotting
Spotting O(n!) in code
| Code shape | What it is | Cost |
|---|---|---|
for i in range(start, n): swap; recurse(start + 1); swap | Swap backtracking | |
for x in remaining: recurse(path + [x], remaining - {x}) | Choose from what is left | |
for p in permutations(items): | Library permutations | iterations |
for i in range(n): recurse(n - 1) | Loop of around a call on | |
recurse(n - 1); recurse(n - 1) | Two calls on | , not factorial |
for mask in range(1 << n): for j in range(n): | Bitmask DP | or |
Common O(n!) problems
Permutations
Generate every ordering of a list: arrangements.
Travelling salesman
Try every route through the cities: tours when distances are symmetric.
Anagrams
All rearrangements of a word: "cat" gives cat, cta, act, atc, tca, tac.
Brute-force assignment
Match jobs to workers by trying every matching.
Recap
Key takeaways
Key points
- counts the orderings of distinct items: 3 give 6, 5 give 120, 10 give 3,628,800.
- O(n!) appears when an algorithm tries every arrangement: permutations, brute-force TSP, brute-force assignment.
- Listing all permutations really costs , because each output has length .
- overtakes at ; Stirling says .
- Brute-force TSP checks distinct tours: fix the start, then halve for direction.
- Practical only up to about to . Beyond that use bitmask DP, a polynomial algorithm or heuristics.