AlgoViz

O(2ⁿ) exponential time

easy 15 min

O(2ⁿ) means the work doubles every time one more item is added.

Video lesson · Chapter 1 of 5

Every habitat switch is independent

0:00 / 4:28

O(2ⁿ) exponential time

1:23Reel

Read caption

Vela visits every on/off configuration with a binary decision tree and a constant-time final check. Another switch doubles the paths.

How it works

Step through the idea, or press Play.

Step 1 of 3

Two choices per item. Take it or leave it, or call yourself twice: every item or level splits the work in two

Understand it

Start here

What O(2ⁿ) means

An algorithm is O(2ⁿ) when the number of operations doubles with each extra input element. Ten items cost about a thousand steps, twenty about a million, thirty about a billion. It is the usual cost of brute-force solutions that try every combination, including the brute force for many NP-hard problems.

  • Two choices per item

    Include or exclude, left or right, call or skip: each binary decision doubles the number of paths.

  • +1 item, ×2 work

    Going from nn to n+1n + 1 doubles the cost, because 2n+1=2⋅2n2^{n+1} = 2 \cdot 2^n.

  • Small n only

    Fine for n≤20n \le 20 or so, hopeless beyond about 40 without a smarter idea.

Where the 2ⁿ comes from

2×2×⋯×2⏟n items=2n\underbrace{2 \times 2 \times \cdots \times 2}_{n \text{ items}} = 2^n
Each of the nn items has 2 choices, and the choices are independent, so the counts multiply. For {A,B,C}\{A, B, C\} that is 23=82^3 = 8 subsets.

The picture

The binary tree of choices

Include or exclude, for A, B and C

Each level decides one item (the last level decides C: left branch leaves it, right branch takes it). Three levels give 23=82^3 = 8 leaves, and every leaf is a different subset.

Every node in the tree

1+2+4+⋯+2n=2n+1−1=O(2n)1 + 2 + 4 + \cdots + 2^n = 2^{n+1} - 1 = O(2^n)
Level kk has 2k2^k nodes. Adding all levels gives just under twice the number of leaves: 15 nodes for 3 items. The leaves dominate, so the whole tree is still O(2n)O(2^n).

Scale

The exponential explosion

n2n2^nTime at 1 µs per step
101,024about 1 ms
201,048,576about 1 second
301,073,741,824about 18 minutes
40about 1.1 trillionabout 13 days
50about 1.1 quadrillionabout 36 years
Just 10 more items multiply the time by about a thousand.

Why +10 means ×1,000

2n+10=210⋅2n=1024⋅2n2^{n+10} = 2^{10} \cdot 2^n = 1024 \cdot 2^n
A computer twice as fast buys you exactly one more item. A thousand times faster buys about ten.

Example 1

Generating every subset

Python
def generate_subsets(items):    result = []    def backtrack(i, current):        if i == len(items):            result.append(current[:])   # a leaf: one full subset            return        backtrack(i + 1, current)       # leave items[i] out        current.append(items[i])        # take items[i]        backtrack(i + 1, current)        current.pop()                   # undo the choice    backtrack(0, [])    return resultsubsets = generate_subsets(["A", "B", "C"])print(subsets)        # [[], ['C'], ['B'], ['B', 'C'], ['A'], ['A', 'C'], ['A', 'B'], ['A', 'B', 'C']]print(len(subsets))   # 8 = 2 ** 3
Backtracking: leave the item out, then take it, then undo. The leaves come out in counting order: { }, {C}, {B}, {B, C}, {A}, ...
Edit and run it in your browser

Each subset is a binary number

Mask (A B C)NumberSubsetMask (A B C)NumberSubset
0000{ }1004{A}
0011{C}1015{A, C}
0102{B}1106{A, B}
0113{B, C}1117{A, B, C}
Counting from 0 to 2n−12^n - 1 in binary visits every subset once, which is why for mask in range(1 << n) is another way to write the same search.

Total work

2n⏟subsets×O(n)⏟copy each=O(n⋅2n)\underbrace{2^n}_{\text{subsets}} \times \underbrace{O(n)}_{\text{copy each}} = O(n \cdot 2^n)
There are 2n2^n answers and each can hold up to nn items, so the output alone is O(n⋅2n)O(n \cdot 2^n). The recursion stack is only O(n)O(n) deep.

Example 2

Naive Fibonacci

The cost recurrence

T(n)=T(n−1)+T(n−2)+O(1),T(0)=T(1)=O(1)T(n) = T(n-1) + T(n-2) + O(1), \qquad T(0) = T(1) = O(1)
Each call does a constant amount of work and makes two more calls. The recurrence has the same shape as Fibonacci itself, so the cost grows like the Fibonacci numbers.

The call tree of fib(5)

15 calls to find fib(5) = 5, but only 6 distinct values exist. The dashed nodes repeat work already done: fib(3) runs twice, fib(2) three times, fib(1) five times.

Tighter than 2ⁿ: the golden ratio

calls(n)=2F(n+1)−1=Θ(φn),φ=1+52≈1.618\text{calls}(n) = 2F(n+1) - 1 = \Theta(\varphi^n), \qquad \varphi = \frac{1 + \sqrt{5}}{2} \approx 1.618
fib(5) makes 2⋅8−1=152 \cdot 8 - 1 = 15 calls, fib(20) makes 21,891 and fib(40) about 331 million. The growth rate is φn\varphi^n, which lies between 2n/2≈1.414n2^{n/2} \approx 1.414^n and 2n2^n. Saying O(2n)O(2^n) is a correct upper bound; Θ(φn)\Theta(\varphi^n) is the exact rate.

The fix

Memoisation turns it into O(n)

A memoised call

Each value is computed once and looked up every time after that. For fib(5) the second fib(3) and fib(2) become instant hits.
Python
calls = {"naive": 0, "memo": 0}def fib(n):    calls["naive"] += 1    if n <= 1:        return n    return fib(n - 1) + fib(n - 2)def fib_memo(n, memo=None):    calls["memo"] += 1    if memo is None:        memo = {}    if n in memo:        return memo[n]    if n <= 1:        return n    memo[n] = fib_memo(n - 1, memo) + fib_memo(n - 2, memo)    return memo[n]print(fib(5), fib_memo(5), calls)    # 5 5 {'naive': 15, 'memo': 9}calls = {"naive": 0, "memo": 0}print(fib(25), fib_memo(25), calls)  # 75025 75025 {'naive': 242785, 'memo': 49}
Count the calls each way. Memoised fib(n) makes 2n - 1 calls and computes only n + 1 distinct values.
Edit and run it in your browser

Why memoisation gives O(n)

time=(n+1)⏟distinct subproblems×O(1)⏟work each=O(n)\text{time} = \underbrace{(n + 1)}_{\text{distinct subproblems}} \times \underbrace{O(1)}_{\text{work each}} = O(n)
Memoised time is the number of distinct subproblems times the work per subproblem. Naive recursion pays for every path through the tree instead, which is exponential.

Memoised or bottom-up: O(n)

  • Each fib(k) is computed once and stored.
  • fib(5) takes 9 calls, fib(40) takes 79.
  • A bottom-up loop keeps only the last two values: O(1)O(1) space.

Naive recursion: O(2ⁿ)

  • The same values are recomputed again and again.
  • fib(5) takes 15 calls, fib(40) about 331 million.
  • The work grows by about 1.6 times for each +1 to nn.

Example 3

Combinations: choosing k of n

Choosing 2 of [1, 2, 3, 4] gives 6 combinations: [1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]. Backtracking picks a first number and then only looks to its right, so no pair appears twice. For a small fixed kk this is polynomial, but over all kk, or for kk near n/2n/2, the count becomes exponential.

All the k's together are the subsets

∑k=0n(nk)=2n(40)+(41)+(42)+(43)+(44)=1+4+6+4+1=16\sum_{k=0}^{n} \binom{n}{k} = 2^n \qquad \binom{4}{0} + \binom{4}{1} + \binom{4}{2} + \binom{4}{3} + \binom{4}{4} = 1 + 4 + 6 + 4 + 1 = 16
Every subset has some size kk, so counting subsets by size adds back up to 2n2^n.

The middle term is exponential on its own

(nn/2)≈2nπn/2\binom{n}{n/2} \approx \frac{2^n}{\sqrt{\pi n / 2}}
The biggest single term carries a large share of all 2n2^n subsets. (2010)=184,756\binom{20}{10} = 184{,}756 and (3015)=155,117,520\binom{30}{15} = 155{,}117{,}520.
Choosen = 10n = 20n = 30Growth
k=2k = 245190435O(n2)O(n^2)
k=3k = 31201,1404,060O(n3)O(n^3)
k=n/2k = n/2252184,756155,117,520about 2n/n2^n / \sqrt{n}
any kk (all subsets)1,0241,048,5761,073,741,8242n2^n

Comparison

2ⁿ next to its neighbours

Classn = 10n = 20n = 30Typical example
O(n2)O(n^2)100400900Checking every pair
O(n3)O(n^3)1,0008,00027,000Three nested loops
O(2n)O(2^n)1,024about 1 millionabout 1 billionEvery subset, naive Fibonacci
O(n!)O(n!)3,628,800about 2.4×10182.4 \times 10^{18}about 2.7×10322.7 \times 10^{32}Every ordering (permutations)
Exponential beats every polynomial in the long run, and factorial beats exponential.

When 2ⁿ overtakes n²

23=8<9=32,24=16=42,2n>n2 for all n≥52^3 = 8 < 9 = 3^2, \qquad 2^4 = 16 = 4^2, \qquad 2^n > n^2 \text{ for all } n \ge 5
For tiny inputs the exponential can even be cheaper. From n=5n = 5 on it pulls ahead and the ratio 2n/n22^n / n^2 grows without limit.

Taming it

How to escape exponential time

Choosing a technique

Memoisation and DP remove the repeats. Pruning and meet in the middle shrink the search but stay exponential.
  • Memoisation

    Cache each subproblem's result. Fibonacci goes from O(2n)O(2^n) to O(n)O(n).

  • Dynamic programming

    Build answers from smaller ones. Subset sum becomes O(n⋅target)O(n \cdot \text{target}).

  • Pruning

    Stop exploring a branch as soon as it cannot lead to an answer. Faster, still exponential at worst.

  • Meet in the middle

    Split the items in half, enumerate each half, and combine: 2n2^n becomes about 2n/22^{n/2}.

Before and after

ProblemBrute forceBetter
FibonacciO(2n)O(2^n) naive recursionO(n)O(n) with memoisation
Subset sumO(2n)O(2^n) try every subsetO(n⋅target)O(n \cdot \text{target}) with DP
Two SumO(n2)O(n^2) try every pairO(n)O(n) with a hash map
Subset sum, n = 40, huge valuesO(2n)O(2^n)about O(2n/2)O(2^{n/2}) meet in the middle
Two Sum's brute force is quadratic, not exponential; it is here because the same idea, remembering what you have seen, fixes it.

Pattern spotting

Spotting O(2ⁿ) in code

Code shapeWhat it isCost
return f(n - 1) + f(n - 2)Two calls, no cacheO(2n)O(2^n)
return f(n - 1) + f(n - 1)Two identical callsΘ(2n)\Theta(2^n); one call doubled is O(n)O(n)
skip(i + 1); take(i + 1)Include or exclude backtrackingO(2n)O(2^n) paths
for mask in range(1 << n)Every bit maskO(2n)O(2^n), or O(n⋅2n)O(n \cdot 2^n) with an inner loop
@lru_cache on f(n - 1) + f(n - 2)Memoised recursionO(n)O(n)
for i ... for j ...Every pairO(n2)O(n^2), not exponential

Is this exponential?

Two calls on n−1n - 1 or n−2n - 2 explode; two calls on n/2n/2 (merge sort) do not, because the depth is only log⁡n\log n.

In the wild

Where exponential time shows up

  • Subset sum and knapsack

    Trying every subset of items to hit a target or fill a bag is the textbook 2n2^n brute force.

  • N-Queens and Sudoku

    Backtracking solvers explore a tree of choices and prune bad branches early.

  • Brute-force key search

    A 128-bit key has 2128≈3.4×10382^{128} \approx 3.4 \times 10^{38} values, which is why guessing it is hopeless.

  • SAT solvers

    nn true or false variables give 2n2^n assignments; real solvers prune and learn to avoid most of them.

  • Traveling salesman

    Brute force tries every route (n!n!); Held-Karp DP over subsets brings it to O(n22n)O(n^2 2^n).

  • Feature flag testing

    Testing every on/off mix of nn flags needs 2n2^n runs, so teams test pairs instead.

Recap

Key takeaways

Key points

  • O(2ⁿ) means each extra item doubles the work: 2n+1=2⋅2n2^{n+1} = 2 \cdot 2^n.
  • It comes from two choices per item or two recursive calls per call; the choice tree has 2n2^n leaves.
  • A set of nn items has 2n2^n subsets; listing them all costs O(n⋅2n)O(n \cdot 2^n).
  • Naive Fibonacci follows T(n)=T(n−1)+T(n−2)+O(1)T(n) = T(n-1) + T(n-2) + O(1) and grows like φn≈1.618n\varphi^n \approx 1.618^n: 15 calls for fib(5).
  • Memoisation computes each subproblem once, turning Fibonacci into O(n)O(n); DP, pruning and meet in the middle tame other cases.
  • Practical limit: n≈20n \approx 20 to 25. +10 items is ×1,000 the work.

Sources