Simple Algorithm
Algorithms & Data Structures · Optimized · 22 min

Recursion & Recurrences

Functions that call themselves, and the equations that count their cost.

Naive recursive Fibonacci makes 331,160,281 calls to compute F40F_{40}, while recursive merge sort sorts a million items with only 20 levels of calls. Both are recursion. The difference is in an equation that counts the calls, and this lesson teaches you to write that equation from code and to solve it.

What you’ll learn

  • Write recursive functions with a base case, a recursive case and guaranteed progress, and prove them correct by induction.
  • Predict the depth of the call stack, and turn recursion that is too deep into a loop with an explicit stack.
  • Prove that the Tower of Hanoi needs exactly 2n−12^n-1 moves, and turn recursive code into a recurrence.
  • Solve recurrences by unrolling, recursion trees and substitution, and apply the master theorem to T(n)=aT(n/b)+Θ(nc)T(n)=aT(n/b)+\Theta(n^c).
  • Recognize problems with self-similar structure, and the two traps: overlapping subproblems and deep stacks.

Anatomy of a recursive function

A recursive function solves a problem by solving smaller instances of the same problem. Every correct one has three parts:

  • a base case, small enough to answer directly;
  • a recursive case, which calls the function on smaller inputs and combines their answers;
  • progress: every chain of calls reaches a base case after finitely many steps.

The correctness proof is induction on the input size. The base case is right by inspection, and if every call on a smaller input returns the right answer, the recursive case combines them into the right answer for nn.

python
def factorial(n):                # n >= 0
    if n == 0:                   # base case
        return 1
    return n * factorial(n - 1)  # recursive case: n - 1 is closer to 0

def power(x, n):                 # x**n for an integer n >= 0
    if n == 0:
        return 1
    half = power(x, n // 2)      # ONE call on n // 2, used twice
    return half * half if n % 2 == 0 else half * half * x

For n≥1n\ge1, power makes ⌊log⁡2n⌋+2\lfloor\log_2 n\rfloor+2 calls instead of n−1n-1 multiplications: halving the exponent is its progress. Writing power(x, n // 2) * power(x, n // 2) would still be correct, but the two calls per level would bring back Θ(n)\Theta(n) calls in total.

Think first A function sums the even numbers up to nn as f(n) = n + f(n - 2), with the base case f(0) = 0. What happens when it is called with n=7n=7?

The chain 7,5,3,1,−1,−3,…7, 5, 3, 1, -1, -3, \dots jumps over the base case and never reaches it, so the calls continue until the stack overflows. Progress means reaching a base case, not just getting smaller. A base case that every chain hits, such as if n <= 0: return 0, fixes it.

The call stack and its limits

Each call gets a stack frame on the call stack: its arguments, its local variables and the place to return to. The frame lives until the call returns. A recursive function's extra memory is therefore its maximum depth times the frame size, which is not its number of calls: factorial(n) is n+1n+1 frames deep, power(x, n) about log⁡2n\log_2 n, and a function that makes a million calls can still be shallow.

The fix that always works is to keep the stack yourself. Flood fill, recoloring the region of equal cells around a starting cell, is the classic case: the recursive version is a few lines, but its depth can reach the number of cells, so a 100×100100\times100 grid of one color already exceeds Python's default limit.

python
def fill_recursive(grid, r, c, old, new):   # needs old != new, or it never stops
    if not (0 <= r < len(grid) and 0 <= c < len(grid[0])) or grid[r][c] != old:
        return
    grid[r][c] = new
    for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
        fill_recursive(grid, r + dr, c + dc, old, new)

def fill_iterative(grid, r, c, new):
    old = grid[r][c]
    if old == new:
        return
    stack = [(r, c)]                 # the explicit stack replaces the call stack
    while stack:
        r, c = stack.pop()
        if 0 <= r < len(grid) and 0 <= c < len(grid[0]) and grid[r][c] == old:
            grid[r][c] = new
            stack.extend([(r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)])

The explicit stack holds what the frames would have held: the cells still to visit. A Python list lives on the heap, which has room for millions of entries, so fill_iterative recolors a 1000×10001000\times1000 grid without trouble. Popping from the end visits cells depth-first; a queue would visit them breadth-first and recolor the same region.

Divide and conquer, and the Tower of Hanoi

Recursive algorithms split their input in a few typical shapes, and the shape decides the cost. power makes one call on half the input. Summing an array by halves makes two calls on halves, and so does merge sort, which then combines the sorted halves with a linear-time merge: this is divide and conquer. The Tower of Hanoi makes two calls on inputs only one smaller, and that turns out to be expensive.

The puzzle: nn disks of different sizes sit on peg A, the largest at the bottom. Move them all to peg C, one disk at a time, never putting a disk on a smaller one; peg B is a spare. The recursive solution is one sentence: move the top n−1n-1 disks out of the way onto B, move the largest disk to C, then move the n−1n-1 disks from B onto it.

python
def hanoi(n, src, dst, via, moves):
    if n == 0:
        return
    hanoi(n - 1, src, via, dst, moves)   # park n - 1 disks on the spare peg
    moves.append((src, dst))             # move the largest disk
    hanoi(n - 1, via, dst, src, moves)   # bring the n - 1 disks on top of it

hanoi(3, 'A', 'C', 'B', moves) produces A→C, A→B, C→B, A→C, B→A, B→C, A→C: seven moves.

DerivationExactly 2ⁿ − 1 moves, and no fewer
  1. M(n)=2M(n−1)+1M(n)=2M(n-1)+1

    The algorithm's count. Let M(n)M(n) be the number of moves hanoi makes. Two recursive calls and one move of the largest disk give a recurrence, with M(0)=0M(0)=0:

  2. M(n)=2n−1M(n)=2^n-1

    Solve it. Add 1 to both sides: M(n)+1=2(M(n−1)+1)M(n)+1=2\big(M(n-1)+1\big). So M(n)+1M(n)+1 doubles at every step, starting from M(0)+1=1M(0)+1=1:

  3. L(n) ≥ 2L(n−1)+1⟹L(n) ≥ 2n−1L(n)\ \ge\ 2L(n-1)+1\quad\Longrightarrow\quad L(n)\ \ge\ 2^n-1

    No algorithm does better. Let L(n)L(n) be the true minimum. The largest disk moves at least once. Just before its first move, the other n−1n-1 disks must all sit on the third peg, since they can be neither on top of it nor on its destination, and getting them there takes at least L(n−1)L(n-1) moves. After its last move, all n−1n-1 disks must be brought onto it: at least L(n−1)L(n-1) more.

  4. 264−1≈1.8×1019 moves ≈ 5.8×1011 years2^{64}-1\approx1.8\times10^{19}\ \text{moves}\ \approx\ 5.8\times10^{11}\ \text{years}

    So the recursive algorithm is optimal. For the legendary 64 disks, at one move per second:

Think first How many moves does an optimal solution with 10 disks need, and with 11?

210−1=10232^{10}-1=1023, and 2⋅1023+1=20472\cdot1023+1=2047: each extra disk doubles the work and adds one move. Two calls on inputs only one smaller always cost exponential time, which is why the shape of a recursion matters more than the length of its code.

From code to recurrence, and solving it

To analyze recursive code, charge each call only for its own work and write the cost of the recursive calls as the unknown function itself. The result is a recurrence:

CodeRecurrenceSolution
power(x, n)T(n)=T(⌊n/2⌋)+Θ(1)T(n)=T(\lfloor n/2\rfloor)+\Theta(1)Θ(log⁡n)\Theta(\log n)
sum of an array by halvesT(n)=T(⌊n/2⌋)+T(⌈n/2⌉)+Θ(1)T(n)=T(\lfloor n/2\rfloor)+T(\lceil n/2\rceil)+\Theta(1)Θ(n)\Theta(n)
merge sortT(n)=T(⌊n/2⌋)+T(⌈n/2⌉)+Θ(n)T(n)=T(\lfloor n/2\rfloor)+T(\lceil n/2\rceil)+\Theta(n)Θ(nlog⁡n)\Theta(n\log n)
find the maximum, recurse on the restT(n)=T(n−1)+Θ(n)T(n)=T(n-1)+\Theta(n)Θ(n2)\Theta(n^2)
hanoi(n)T(n)=2T(n−1)+Θ(1)T(n)=2T(n-1)+\Theta(1)Θ(2n)\Theta(2^n)
naive fib(n)T(n)=T(n−1)+T(n−2)+Θ(1)T(n)=T(n-1)+T(n-2)+\Theta(1)Θ(φn)\Theta(\varphi^n)
The base cases cost Θ(1)\Theta(1) and are usually left implicit. Floors and ceilings rarely change the answer by more than a constant factor.

Three methods solve almost every recurrence you will meet.

Unrolling: expand until a pattern appears. T(n)=T(n−1)+n=T(n−2)+(n−1)+n=⋯=T(0)+n(n+1)/2T(n)=T(n-1)+n=T(n-2)+(n-1)+n=\dots=T(0)+n(n+1)/2, so T(n)=Θ(n2)T(n)=\Theta(n^2).

Recursion trees: draw the calls as a tree, write each node's own work, and sum level by level. For T(n)=2T(n/2)+nT(n)=2T(n/2)+n, level jj holds 2j2^j calls on inputs of size n/2jn/2^j, which costs nn in total, and there are log⁡2n+1\log_2 n+1 levels. With T(1)=1T(1)=1 and nn a power of two, T(n)=nlog⁡2n+nT(n)=n\log_2 n+n exactly.

Substitution: guess the answer, then prove it by induction. The substitution method is the only one of the three that is a proof by itself, and it has one classic trap.

DerivationSubstitution for T(n) = 2T(n/2) + n, with T(1) = 1
  1. T(n) ≤ 2c n2log⁡2n2+n = c nlog⁡2n−c n+n ≤ c nlog⁡2nif c≥1T(n)\ \le\ 2c\,\tfrac n2\log_2\tfrac n2+n\ =\ c\,n\log_2 n-c\,n+n\ \le\ c\,n\log_2 n\quad\text{if } c\ge1

    Guess T(n)≤c nlog⁡2nT(n)\le c\,n\log_2 n for all powers of two n≥2n\ge2. Inductive step, for n≥4n\ge4: assume the bound for n/2n/2 and substitute it.

  2. T(n) ≤ 2nlog⁡2n = O(nlog⁡n)T(n)\ \le\ 2n\log_2 n\ =\ O(n\log n)

    Base case: T(2)=2T(1)+2=4T(2)=2T(1)+2=4, and 4≤c⋅2log⁡22=2c4\le c\cdot2\log_2 2=2c holds for c≥2c\ge2. So c=2c=2 works for every power of two n≥2n\ge2:

  3. T(n) ≤ 2c n2+n = (c+1) n ≰ c nT(n)\ \le\ 2c\,\tfrac n2+n\ =\ (c+1)\,n\ \not\le\ c\,n

    The classic mistake is to "prove" T(n)=O(n)T(n)=O(n) by assuming T(n/2)≤c n/2T(n/2)\le c\,n/2 and concluding T(n)≤(c+1)n=O(n)T(n)\le(c+1)n=O(n). The induction must return the bound with the same constant, T(n)≤c nT(n)\le c\,n, and that fails:

Naive Fibonacci is the warning example. It computes Fn−2F_{n-2} inside the call for Fn−1F_{n-1} and then again directly: the subproblems overlap. With base cases F0=0F_0=0 and F1=1F_1=1, its number of calls satisfies C(0)=C(1)=1C(0)=C(1)=1 and C(n)=C(n−1)+C(n−2)+1C(n)=C(n-1)+C(n-2)+1.

Predict before you look

Using C(0)=C(1)=1C(0)=C(1)=1 and C(n)=C(n−1)+C(n−2)+1C(n)=C(n-1)+C(n-2)+1, how many calls does the naive recursion make to compute F10=55F_{10}=55?

Show the answer

177

CC runs 1,1,3,5,9,15,25,41,67,109,1771, 1, 3, 5, 9, 15, 25, 41, 67, 109, 177. Adding 1 to both sides shows that C(n)+1C(n)+1 obeys the Fibonacci recurrence, so C(n)=2Fn+1−1C(n)=2F_{n+1}-1: here 2⋅89−1=1772\cdot89-1=177. The calls grow like φn\varphi^n, where φ=(1+5)/2≈1.618\varphi=(1+\sqrt5)/2\approx1.618 is the golden ratio: C(40)=331,160,281C(40)=331{,}160{,}281.

Think first Summing an array by halves, T(n)=2T(n/2)+Θ(1)T(n)=2T(n/2)+\Theta(1), has only about log⁡2n\log_2 n levels of calls. Why does it still take Θ(n)\Theta(n) time?

Time is the number of calls times the work per call, not the depth. The tree has nn leaves and n−1n-1 internal calls, 2n−12n-1 in all, each doing constant work. The depth, Θ(log⁡n)\Theta(\log n), bounds the memory on the stack, not the time.

The master theorem

Divide-and-conquer recurrences have the form T(n)=aT(n/b)+f(n)T(n)=aT(n/b)+f(n): aa subproblems of size n/bn/b, plus f(n)f(n) work to split and combine. When f(n)=Θ(nc)f(n)=\Theta(n^c), the recursion tree settles everything. Level jj has aja^j calls of size n/bjn/b^j, so it costs

aj(nbj)c=nc(abc)j,a^j\Big(\frac{n}{b^j}\Big)^c=n^c\Big(\frac{a}{b^c}\Big)^j,

a geometric series with ratio a/bca/b^c over about log⁡bn\log_b n levels. The bottom level has alog⁡bn=nlog⁡baa^{\log_b n}=n^{\log_b a} leaves. The ratio is below 1, equal to 1 or above 1 exactly when cc is above, equal to or below log⁡ba\log_b a.

RecurrenceWhere it comes froma, b, ca,\ b,\ c and log⁡ba\log_b aSolution
T(n/2)+1T(n/2)+1binary search1, 2, 01,\ 2,\ 0; log⁡21=0\log_2 1=0case 2: Θ(log⁡n)\Theta(\log n)
2T(n/2)+12T(n/2)+1sum by halves, tree traversal2, 2, 02,\ 2,\ 0; 11case 1: Θ(n)\Theta(n)
2T(n/2)+n2T(n/2)+nmerge sort2, 2, 12,\ 2,\ 1; 11case 2: Θ(nlog⁡n)\Theta(n\log n)
3T(n/2)+n3T(n/2)+nKaratsuba multiplication3, 2, 13,\ 2,\ 1; ≈1.585\approx1.585case 1: Θ(nlog⁡23)\Theta(n^{\log_2 3})
7T(n/2)+n27T(n/2)+n^2Strassen matrix multiplication7, 2, 27,\ 2,\ 2; ≈2.807\approx2.807case 1: Θ(nlog⁡27)\Theta(n^{\log_2 7})
2T(n/2)+n22T(n/2)+n^2quadratic combine step2, 2, 22,\ 2,\ 2; 11case 3: Θ(n2)\Theta(n^2)

The theorem does not cover these, and each has its own tool:

  • T(n)=T(n−1)+nT(n)=T(n-1)+n shrinks by subtraction, not division. Unroll it: Θ(n2)\Theta(n^2).
  • T(n)=2T(n/2)+n/log⁡nT(n)=2T(n/2)+n/\log n falls in a gap: f(n)f(n) is below nlog⁡22=nn^{\log_2 2}=n, but not by a polynomial factor. The recursion tree's level costs are n/log⁡2(n/2j)n/\log_2(n/2^j), a harmonic sum, giving Θ(nlog⁡log⁡n)\Theta(n\log\log n).
  • T(n)=T(n/3)+T(2n/3)+nT(n)=T(n/3)+T(2n/3)+n splits unequally. Every full level costs nn, and there are between log⁡3n\log_3 n and log⁡3/2n\log_{3/2}n levels: Θ(nlog⁡n)\Theta(n\log n).
  • T(n)=2T(n)+log⁡2nT(n)=2T(\sqrt n)+\log_2 n shrinks by a square root. Set m=log⁡2nm=\log_2 n and S(m)=T(2m)S(m)=T(2^m): then S(m)=2S(m/2)+mS(m)=2S(m/2)+m, so T(n)=Θ(log⁡n⋅log⁡log⁡n)T(n)=\Theta(\log n\cdot\log\log n).
Check your understanding

What is the solution of T(n)=4T(n/2)+n2T(n)=4T(n/2)+n^2?

  1. Θ(n2)\Theta(n^2)
  2. Θ(n2log⁡n)\Theta(n^2\log n)
  3. Θ(n3)\Theta(n^3)
  4. Θ(nlog⁡n)\Theta(n\log n)
Show the answer

B. Θ(n2log⁡n)\Theta(n^2\log n)

log⁡24=2=c\log_2 4=2=c: case 2. Every level costs 4j(n/2j)2=n24^j(n/2^j)^2=n^2, and there are about log⁡2n\log_2 n levels, so T(n)=Θ(n2log⁡n)T(n)=\Theta(n^2\log n).

Recognizing it

Reach for recursion when the problem is self-similar: the answer for the whole is built from answers for parts of the same kind. The signals in a statement:

  • the input is recursive by nature: a tree, a nested list, an expression with brackets, a directory hierarchy;
  • a big instance splits into halves that are solved the same way (sorting, counting pairs across two halves, closest points);
  • "list or count all subsets, permutations or arrangements" with n≤20n\le20 or so: recursion that makes one choice per level, which is backtracking;
  • a quantity can be halved: an exponent, a search range.
Problem (in brief)Recursive ideaCost
Height of a binary treeh(t)=1+max⁡(h(left),h(right))h(t)=1+\max\big(h(\text{left}),h(\text{right})\big), empty tree −1-1Θ(n)\Theta(n) time; depth = height, up to nn
xy mod mx^y \bmod m with yy up to 101810^{18}square the result for ⌊y/2⌋\lfloor y/2\rfloor; multiply by xx if yy is oddO(log⁡y)O(\log y) multiplications
Count the inversions of an arraymerge sort that also counts the pairs that cross the two halvesT(n)=2T(n/2)+Θ(n)=Θ(nlog⁡n)T(n)=2T(n/2)+\Theta(n)=\Theta(n\log n)
All subsets of n≤20n\le20 items with a propertyinclude or exclude item ii, then recurse on i+1i+1Θ(2n)\Theta(2^n) leaves
Evaluate a nested expression like (2+(3*4))an expression is a number or a bracketed pair of expressionsΘ(length)\Theta(\text{length})
The depth column matters as much as the time: a recursive tree walk on a path-shaped tree of 10510^5 nodes is 10510^5 frames deep.

Common bugs

  • A base case that some inputs skip, like n - 2 jumping over 0 for odd nn, or a missing case for the empty input.
  • No progress: a range that does not shrink. With mid = (lo + hi) // 2 on the inclusive range [lo,hi][lo, hi] with hi=lo+1hi=lo+1, recursing on [mid,hi][mid, hi] calls itself on the same range forever.
  • Forgetting to return the recursive result: in Python the function then returns None.
  • Backtracking that changes shared state (a list, a "used" array) and does not undo the change after the call.
  • A memo dictionary declared as a default argument, def f(n, memo={}), which survives between test cases.
  • Exponential blowup from overlapping subproblems, and stack overflow from linear depth.
Check your understanding

You must list every subset of n≤15n\le15 items whose weights sum exactly to a target. Which approach fits?

  1. A recursion that includes or excludes each item in turn, one item per level
  2. The master theorem with a=2a=2, b=2b=2
  3. Binary search on the target
  4. A single loop that adds the items in sorted order
Show the answer

A. A recursion that includes or excludes each item in turn, one item per level

The answer may be any of the 215=32,7682^{15}=32{,}768 subsets, and a recursion that branches on "take item ii or not" visits each exactly once, at depth at most 15. This is backtracking, and it can also prune a branch as soon as its sum exceeds the target (with positive weights).

Key takeaways

  • A recursive function needs a base case, a recursive case on smaller inputs, and progress toward the base case; its correctness proof is induction on the input size.
  • Memory is the maximum depth of the call stack, not the number of calls. Python stops at 1000 frames by default, and an explicit stack turns any recursion into a loop.
  • The Tower of Hanoi needs exactly 2n−12^n-1 moves: the recurrence M(n)=2M(n−1)+1M(n)=2M(n-1)+1 counts the algorithm, and an argument about the largest disk shows nothing does better.
  • Solve recurrences by unrolling, recursion trees, or substitution, where the induction must return the same constant. Overlapping subproblems make naive recursion exponential: Fibonacci makes 2Fn+1−12F_{n+1}-1 calls.
  • Master theorem: T(n)=aT(n/b)+Θ(nc)T(n)=aT(n/b)+\Theta(n^c) is Θ(nlog⁡ba)\Theta(n^{\log_b a}), Θ(nclog⁡n)\Theta(n^c\log n) or Θ(nc)\Theta(n^c) as cc is below, equal to or above log⁡ba\log_b a. It does not cover subtraction, unequal splits or the gaps between cases.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

What does the master theorem give for T(n)=8T(n/2)+n2T(n)=8T(n/2)+n^2?

  1. Θ(n2log⁡n)\Theta(n^2\log n)
  2. Θ(n3)\Theta(n^3)
  3. Θ(n2)\Theta(n^2)
  4. Θ(n3log⁡n)\Theta(n^3\log n)
Show the answer

B. Θ(n3)\Theta(n^3)

Here a=8a=8, b=2b=2, c=2c=2, and log⁡28=3>2\log_2 8=3>2. Level jj of the recursion tree costs n2 (8/4)j=n2 2jn^2\,(8/4)^j=n^2\,2^j, a geometric series that grows toward the leaves, so the nlog⁡28=n3n^{\log_2 8}=n^3 leaves dominate: Θ(n3)\Theta(n^3).

Question 2

Why can no strategy solve the Tower of Hanoi with fewer than 2n−12^n-1 moves?

  1. Because the recursive algorithm makes 2n−12^n-1 moves, and recursive algorithms are optimal
  2. Because there are 2n2^n ways to arrange the disks
  3. Because before the largest disk's first move, and after its last, all n−1n-1 other disks must be moved as a whole tower
  4. Because the master theorem gives Θ(2n)\Theta(2^n)
Show the answer

C. Because before the largest disk's first move, and after its last, all n−1n-1 other disks must be moved as a whole tower

Before its first move, the largest disk's source and destination must be free of smaller disks, so the other n−1n-1 disks all sit on the third peg; after its last move they must all come onto it. That gives L(n)≥2L(n−1)+1L(n)\ge2L(n-1)+1, hence L(n)≥2n−1L(n)\ge2^n-1, which the recursive algorithm achieves.

Question 3

A recursive depth-first search over a tree with 2⋅1052\cdot10^5 nodes crashes in Python with RecursionError when the tree is a long path. What is the most robust fix?

  1. Rewrite the search with an explicit stack in a loop
  2. Add memoization to the recursive function
  3. Call sys.setrecursionlimit(10**9) and keep the recursion
  4. Recurse on the children in the opposite order
Show the answer

A. Rewrite the search with an explicit stack in a loop

The depth of the recursion equals the depth of the tree, 2⋅1052\cdot10^5 on a path. An explicit stack keeps the same information on the heap, with no depth limit and no risk of overflowing the call stack.

Question 4

Which recurrence can the master theorem, in the form T(n)=aT(n/b)+Θ(nc)T(n)=aT(n/b)+\Theta(n^c), solve directly?

  1. T(n)=T(n−1)+nT(n)=T(n-1)+n
  2. T(n)=2T(n/2)+n/log⁡nT(n)=2T(n/2)+n/\log n
  3. T(n)=T(n/3)+T(2n/3)+nT(n)=T(n/3)+T(2n/3)+n
  4. T(n)=9T(n/3)+nT(n)=9T(n/3)+n
Show the answer

D. T(n)=9T(n/3)+nT(n)=9T(n/3)+n

a=9a=9, b=3b=3, c=1c=1 and log⁡39=2>1\log_3 9=2>1: case 1 gives Θ(n2)\Theta(n^2). The others fall outside the theorem: subtraction instead of division (Θ(n2)\Theta(n^2) by unrolling), a non-polynomial gap (Θ(nlog⁡log⁡n)\Theta(n\log\log n)), and unequal parts (Θ(nlog⁡n)\Theta(n\log n)).

Question 5

A student "proves" T(n)=2T(n/2)+nT(n)=2T(n/2)+n is O(n)O(n): assume T(n/2)≤c n/2T(n/2)\le c\,n/2; then T(n)≤c n+n=O(n)T(n)\le c\,n+n=O(n). What is wrong?

  1. Nothing: the bound is correct
  2. The induction must prove T(n)≤c nT(n)\le c\,n with the same constant, but it only gives (c+1) n(c+1)\,n
  3. The base case was not checked
  4. Substitution only works for recurrences with one recursive call
Show the answer

B. The induction must prove T(n)≤c nT(n)\le c\,n with the same constant, but it only gives (c+1) n(c+1)\,n

Each level of the induction would raise the constant by 1, and over log⁡2n\log_2 n levels that is the hidden log⁡n\log n factor. The true solution is Θ(nlog⁡n)\Theta(n\log n), and substitution proves T(n)≤2nlog⁡2nT(n)\le2n\log_2 n correctly.

Go deeper

Further reading

  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapters 2 and 4.
  • J. Erickson, Algorithms (2019), chapter 1, "Recursion", free online at jeffe.cs.illinois.edu.
  • R. L. Graham, D. E. Knuth & O. Patashnik, Concrete Mathematics, 2nd ed. (Addison-Wesley, 1994), chapter 1, "Recurrent Problems".