AlgoViz

O(n!) factorial time

easy 15 min

O(n!) means the work grows like n × (n - 1) × ...

Video lesson · Chapter 1 of 6

Every speaker gets a distinct cue

0:00 / 5:50

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.

Step 1 of 3

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 n!=n×(n−1)×⋯×2×1n! = n \times (n-1) \times \dots \times 2 \times 1, the number of ways to put nn 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 O(2n)O(2^n).

The factorial, defined recursively

n!=n⋅(n−1)!0!=1n! = n \cdot (n-1)! \qquad 0! = 1
Going from n−1n - 1 items to nn items multiplies the count by nn: the new item can be slotted into any of nn positions of every existing arrangement. So each extra item makes the work nn times bigger, not a fixed amount bigger.
  • Every ordering

    Factorial time means visiting all n!n! orderings of the input, one by one.

  • The multiplier grows

    O(2n)O(2^n) doubles per item. O(n!)O(n!) multiplies by nn, so the 11th item multiplies the work by 11.

  • Tiny inputs only

    10!≈3.610! \approx 3.6 million is fine; 13!≈6.213! \approx 6.2 billion takes seconds; 20!20! takes decades.

The picture

The permutation tree

Every ordering of [1, 2, 3]

Level 1 has 3 choices, level 2 has 2, level 3 has 1. The leaves are the 3×2×1=63 \times 2 \times 1 = 6 permutations.

The product rule

n⏟1st slot×(n−1)⏟2nd slot×(n−2)⏟3rd slot×⋯×1⏟last slot=n!\underbrace{n}_{\text{1st slot}} \times \underbrace{(n-1)}_{\text{2nd slot}} \times \underbrace{(n-2)}_{\text{3rd slot}} \times \dots \times \underbrace{1}_{\text{last slot}} = n!
Each level of the tree has one fewer choice because an item, once used, is gone. Multiplying the choices per level counts the leaves.

The math

Counting the real work

Generating all permutations visits every node of the tree, not only the leaves. There are n!/(n−d)!n!/(n-d)! nodes at depth dd, and adding them up gives a little under e⋅n!e \cdot n! calls. Each leaf also copies an array of length nn into the result, so the true cost of listing every permutation is O(n⋅n!)O(n \cdot n!).

Calls in the recursion tree

∑d=0nn!(n−d)!=n!∑k=0n1k!<e⋅n!n=3:  1+3+6+6=16\sum_{d=0}^{n} \frac{n!}{(n-d)!} = n! \sum_{k=0}^{n} \frac{1}{k!} < e \cdot n! \qquad n = 3: \; 1 + 3 + 6 + 6 = 16
The internal nodes add less than a factor of e≈2.72e \approx 2.72, so the number of calls is still O(n!)O(n!).

The recurrence

T(n)=n⋅T(n−1)+O(n)  ⇒  T(n)=O(n⋅n!)T(n) = n \cdot T(n-1) + O(n) \;\Rightarrow\; T(n) = O(n \cdot n!)
A call with nn items left loops nn times and recurses on n−1n - 1 items each time. Compare with T(n)=2 T(n−1)+O(1)T(n) = 2\,T(n-1) + O(1), which gives only O(2n)O(2^n).

Scale

How fast n! explodes

nn!n!At 10910^9 steps per second
5120instant
75,040instant
103,628,800about 4 milliseconds
12479,001,600about half a second
136,227,020,800about 6 seconds
15about 1.3 trillionabout 22 minutes
20about 2.4×10182.4 \times 10^{18}about 77 years
Brute force over orderings is practical up to about n=10n = 10 to 1212. Past that, every extra item multiplies the wait by nn.

Stirling's approximation

n!≈2πn(ne)nn=10:  3,598,696 vs 3,628,800n! \approx \sqrt{2\pi n}\left(\frac{n}{e}\right)^{n} \qquad n = 10: \; 3{,}598{,}696 \text{ vs } 3{,}628{,}800
Within 1% at n=10n = 10 and closer as nn grows. It shows n!n! grows roughly like (n/e)n(n/e)^n: the base itself grows with nn, which is why no fixed cnc^n can keep up.

A bonus: why sorting is n log n

log⁡2n!≈nlog⁡2n−1.44 n=Θ(nlog⁡n)\log_2 n! \approx n \log_2 n - 1.44\,n = \Theta(n \log n)
A comparison sort must tell apart all n!n! possible input orders, and each yes or no comparison at best halves them. That needs log⁡2n!\log_2 n! comparisons, which is where the Ω(nlog⁡n)\Omega(n \log n) lower bound comes from.

Comparison

n! against 2ⁿ

nn2n^22n2^nn!n!n!/2nn! / 2^n
39860.75
41616241.5
525321203.75
101001,0243,628,800about 3,544
1522532,768about 1.3 trillionabout 40 million
20400about 1 millionabout 2.4×10182.4 \times 10^{18}about 2.3 trillion
At n=3n = 3 the factorial is actually the smallest of the three. It overtakes 2n2^n at n=4n = 4 and never looks back.

Why the gap keeps widening

n!2n=12⋅22⋅32⋅42⋯n2\frac{n!}{2^n} = \frac{1}{2} \cdot \frac{2}{2} \cdot \frac{3}{2} \cdot \frac{4}{2} \cdots \frac{n}{2}
Pair each factor of n!n! with one 2. Every factor past k=2k = 2 is bigger than 1, and the factors themselves keep growing, so the ratio grows faster and faster.

The growth ladder

Factorial sits at the top of the ladder you will see in practice. Only O(nn)O(n^n) grows faster, and n!≤nnn! \le n^n always.

Example 1

Generating permutations by swapping

One call of the swap backtracker

Position start is filled by each remaining item in turn. Swapping back restores the array so the next choice starts clean.
Python
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 work
The order comes out as 123, 132, 213, 231, 321, 312. Watch it step by step in the visualizer.
Edit and run it in your browser

Swap in place

  • Uses the input array itself, O(n)O(n) 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 nn 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 n!n! orders, though: two kinds of duplicates can be removed.

Why there are (n-1)!/2 distinct tours

n!n⏟starting city⋅2⏟direction=(n−1)!2n=4:  3!2=3\frac{n!}{\underbrace{n}_{\text{starting city}} \cdot \underbrace{2}_{\text{direction}}} = \frac{(n-1)!}{2} \qquad n = 4: \; \frac{3!}{2} = 3
A loop has no real start: A→B→C→D→A and B→C→D→A→B are the same tour, so fix city 0 as the start and divide by nn. When distances are the same both ways, a tour and its reverse cost the same, so divide by 2.

All (4 - 1)! = 6 routes from city 0

RouteLegsTotal
0 → 1 → 2 → 3 → 010 + 35 + 30 + 2095
0 → 1 → 3 → 2 → 010 + 25 + 30 + 1580
0 → 2 → 1 → 3 → 015 + 35 + 25 + 2095
0 → 2 → 3 → 1 → 015 + 30 + 25 + 1080 (reverse of row 2)
0 → 3 → 1 → 2 → 020 + 25 + 35 + 1595 (reverse of row 3)
0 → 3 → 2 → 1 → 020 + 30 + 35 + 1095 (reverse of row 1)
Six routes, but only three different tours. The shortest loop is 80. At 10 cities there are 181,440 distinct tours; at 20, about 6×10166 \times 10^{16}.
Python
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)
Fixing the start city cuts n! orders to (n - 1)!. The symmetric halving is left out here to keep the code simple.
Edit and run it in your browser

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 O(n)O(n), so stepping through all n!n! of them costs O(n⋅n!)O(n \cdot n!) time but only O(1)O(1) extra space. C++'s std::next_permutation works this way.

Next permutation in four moves

For 1 3 2: i points at 1, j at 2. Swap to get 2 3 1, then reverse the tail to get 2 1 3.
Python
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]]
Starting from sorted order and calling it until it returns False lists all n! permutations in dictionary order.
Edit and run it in your browser

Relatives

Duplicates, derangements and pruning

  • Repeated items

    With duplicates the count drops to n!c1! c2!⋯\frac{n!}{c_1! \, c_2! \cdots}. "AAB" has 3!/2!=33!/2! = 3 orders. Sort, then skip an item equal to its unused left neighbour.

  • Derangements

    Orders where no item stays in its own place. About n!/en!/e of them, so still factorial: D(4)=9D(4) = 9, D(5)=44D(5) = 44.

  • N-Queens

    One queen per row, so the columns form a permutation. Pruning attacked squares cuts most of the n!n! tree, though the worst case stays exponential.

Counting derangements

D(n)=(n−1)(D(n−1)+D(n−2)),D(0)=1,  D(1)=0D(n)≈n!eD(n) = (n-1)\big(D(n-1) + D(n-2)\big), \quad D(0) = 1,\; D(1) = 0 \qquad D(n) \approx \frac{n!}{e}
Item 1 goes to one of n−1n - 1 other places, say place kk. Either item kk swaps straight back (D(n−2)D(n-2) ways) or it does not (D(n−1)D(n-1) ways). Counting this way is O(n)O(n) even though listing them is factorial.

Escape routes

What to do instead of n!

Choosing an approach for an ordering problem

Factorial brute force is a correctness baseline, not a production plan.
ProblemBrute forceBetter
Travelling salesman(n−1)!/2(n-1)!/2 toursHeld-Karp DP O(n2 2n)O(n^2 \, 2^n): about 420 million steps at n=20n = 20
Assign nn jobs to nn workersn!n! matchingsHungarian algorithm O(n3)O(n^3)
Is one string an anagram of another?n!n! rearrangementsCount letters O(n)O(n)
kk-th permutation in orderList kk of themFactorial number system O(n2)O(n^2)
Count arrangementsList them allA formula: n!n!, n!/(c1!⋯ )n!/(c_1! \cdots), D(n)D(n)
At n=20n = 20, Held-Karp's 4.2×1084.2 \times 10^8 steps finish in under a second; brute force's 6×10166 \times 10^{16} tours do not finish this year.

Pattern spotting

Spotting O(n!) in code

Code shapeWhat it isCost
for i in range(start, n): swap; recurse(start + 1); swapSwap backtrackingO(n⋅n!)O(n \cdot n!)
for x in remaining: recurse(path + [x], remaining - {x})Choose from what is leftO(n⋅n!)O(n \cdot n!)
for p in permutations(items):Library permutationsO(n!)O(n!) iterations
for i in range(n): recurse(n - 1)Loop of nn around a call on n−1n - 1O(n!)O(n!)
recurse(n - 1); recurse(n - 1)Two calls on n−1n - 1O(2n)O(2^n), not factorial
for mask in range(1 << n): for j in range(n):Bitmask DPO(n 2n)O(n \, 2^n) or O(n2 2n)O(n^2 \, 2^n)

Common O(n!) problems

  • Permutations

    Generate every ordering of a list: n!n! arrangements.

  • Travelling salesman

    Try every route through the cities: (n−1)!/2(n-1)!/2 tours when distances are symmetric.

  • Anagrams

    All rearrangements of a word: "cat" gives cat, cta, act, atc, tca, tac.

  • Brute-force assignment

    Match nn jobs to nn workers by trying every matching.

Recap

Key takeaways

Key points

  • n!=n⋅(n−1)!n! = n \cdot (n-1)! counts the orderings of nn 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 O(n⋅n!)O(n \cdot n!), because each output has length nn.
  • n!n! overtakes 2n2^n at n=4n = 4; Stirling says n!≈2πn (n/e)nn! \approx \sqrt{2\pi n}\,(n/e)^n.
  • Brute-force TSP checks (n−1)!/2(n-1)!/2 distinct tours: fix the start, then halve for direction.
  • Practical only up to about n=10n = 10 to 1212. Beyond that use bitmask DP, a polynomial algorithm or heuristics.

Sources