AlgoViz

O(2ⁿ) exponential time

easy 15 min

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

See it run

Watch two choices per item double the work: every subset as a bit mask, the naive fib(5) call tree redoing the same calls, combinations by backtracking, and 2ⁿ racing past n².

Operations

Generate all subsets

List every subset of {A, B, C}. Each item is either left out (0) or taken (1), so every subset is a 3-bit mask and there are 2³ = 8 of them.

Step 1 of 10

The problem: the power set of {A, B, C}

421
A B C000nothing chosen yet

3 items → 2³ = 8 masks

For each of the 3 items we make one yes or no decision. Two choices, three times: 2 \times 2 \times 2 = 2^3 = 8 subsets. Write each answer as a bit: 1 = take it, 0 = leave it. The columns are worth 4, 2 and 1, so every subset is also a number from 0 to 7.

Step 1: The problem: the power set of {A, B, C}

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)       # choice 1: leave items[i] out        current.append(items[i])        # choice 2: take items[i]        backtrack(i + 1, current)        current.pop()                   # undo the choice    backtrack(0, [])    return result
Time
O(n · 2ⁿ)
Space
O(n) stack, O(n · 2ⁿ) output
n = 10
1,024 subsets
n = 20
1,048,576 subsets

Two choices per item, n items: 2ⁿ results. You cannot beat O(2ⁿ) when the answer itself has 2ⁿ entries, so the goal is only to avoid wasted work on top.

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Shipping naive recursive Fibonacci

    critical

    fib(n - 1) + fib(n - 2) without a cache recomputes the same values exponentially often. fib(40) makes over 331 million calls and takes many seconds in Python; fib(60) would take years.

    Wrong
    def fib(n):    if n <= 1:        return n    return fib(n - 1) + fib(n - 2)   # O(2^n)
    Right
    from functools import lru_cache@lru_cache(maxsize=None)def fib(n):    if n <= 1:        return n    return fib(n - 1) + fib(n - 2)   # O(n): each n computed once
  • Appending the working list instead of a copy

    critical

    In backtracking, current keeps changing. Appending it directly stores the same list object 2ⁿ times, and after all the pops every stored entry is the empty list.

    Wrong
    if i == len(items):    result.append(current)      # every entry ends up []    return
    Right
    if i == len(items):    result.append(current[:])   # snapshot this subset    return
  • Forgetting to undo a choice

    major

    After exploring the branch that takes an item, the item must be removed before returning. Without the pop, items leak into sibling branches and the subsets come out wrong and too long.

    Wrong
    current.append(items[i])backtrack(i + 1, current)# missing pop: items[i] stays in current
    Right
    current.append(items[i])backtrack(i + 1, current)current.pop()                   # undo before trying the next branch
  • Brute-forcing every subset when n is 40 or more

    major

    2⁴⁰ is about 1.1 trillion. Check the constraints first: n up to about 20 to 25 allows 2ⁿ; bigger n needs DP over a small value range, pruning, or meet in the middle (2^(n/2) per half).

    Wrong
    # n = 40: tries about 1.1 trillion subsetsany(sum(s) == target for s in all_subsets(nums))
    Right
    # subset sum with small non-negative values: O(n * target) DPreach = {0}for x in nums:    reach |= {s + x for s in reach if s + x <= target}found = target in reach
  • Calling a nested pair loop exponential

    minor

    Checking every pair is O(n²), not O(2ⁿ). Exponential means something doubles per extra item, such as the number of subsets. Mixing them up is a common interview slip.

    Wrong
    # "all pairs is O(2^n)"  <- wrongfor i in range(n):    for j in range(i + 1, n):        check(nums[i], nums[j])
    Right
    # all pairs: n(n-1)/2 checks, O(n^2)for i in range(n):    for j in range(i + 1, n):        check(nums[i], nums[j])
  • Hitting the recursion limit after memoising

    minor

    Memoisation fixes the time, but the recursion is still n frames deep. Python's default limit is about 1,000, so fib_memo(5000) raises RecursionError. A bottom-up loop needs no stack at all.

    Wrong
    fib_memo(5000)                 # RecursionError
    Right
    def fib_iter(n):    a, b = 0, 1    for _ in range(n):        a, b = b, a + b           # O(n) time, O(1) space    return a

Interview tips

  • How to explain it

    • O(2ⁿ) means the work doubles every time one more item is added.
    • It comes from two choices per item (take it or leave it) or two recursive calls per call.
    • n = 20 is about a million steps, n = 30 about a billion, n = 40 about a trillion.
    • Naive Fibonacci is really Θ(φⁿ) with φ ≈ 1.618, still exponential; memoisation makes it O(n).
  • Spot it in code

    • A recursive function that calls itself twice on a problem only 1 or 2 smaller.
    • Backtracking with an include branch and an exclude branch per item.
    • `for mask in range(1 << n)`: a loop over every bit mask.
    • Constraints like n ≤ 20 hint that an O(2ⁿ) or O(n · 2ⁿ) solution is expected.
  • Memory tricks

    • Double Trouble: two choices per item, so the tree doubles every level.
    • A family tree doubles each generation: 2 parents, 4 grandparents, 8 great-grandparents.
    • 2¹⁰ ≈ 1 thousand, 2²⁰ ≈ 1 million, 2³⁰ ≈ 1 billion: +10 to n is ×1,000 the work.
  • Watch out

    • Repeated arguments in a recursion tree mean wasted work: memoise or use DP.
    • Pruning makes backtracking faster in practice but the worst case usually stays exponential.
    • C(n, k) is polynomial for fixed k but exponential near k = n/2.