Exercise 20 of 30 · intermediate · recursion · factorial · backtracking

Generating every permutation

The code

def permute(items, i=0):
    if i == len(items):
        output(items)
        return
    for j in range(i, len(items)):
        items[i], items[j] = items[j], items[i]
        permute(items, i + 1)
        items[i], items[j] = items[j], items[i]

How many orderings of n distinct items are there?

Count: permutations output.

Measured counts

110100100010k1.0e+2k1.0M10M510ncount (log scale)
Measured
Table
ncount
22
36
424
5120
6720
75,040
840,320
9362,880
103,628,800
1139,916,800

Try to name the class from the shape before opening the answer.

Show the answer and derivation
Time
Θ(n · n!) with output
Extra space
Θ(n) stack
Exact count
n!
  1. n choices for position 0, n − 1 for position 1, …: n! permutations.
  2. n! outgrows 2ⁿ quickly: 10! = 3,628,800, 20! ≈ 2.4 × 10¹⁸.
  3. This is why "try every order" fails beyond about n = 11 on a typical machine.

Common mistake: Treating n! as roughly 2ⁿ. By n = 20, n! is about 2 × 10¹² times larger than 2ⁿ.

Check: measured count ÷ (n!) settles near 1.00 for large n (growth factors are compared for exponential classes).