TExcelTAD
Home › Foundations of Algorithm Analysis › The Master Theorem

The Master Theorem

Most divide-and-conquer recurrences have the same shape, T(n)=aT(n/b)+f(n)T(n) = aT(n/b) + f(n), and their recursion trees always come out in one of three pictures: the levels shrink, stay level, or grow. The master theorem records the answer for each picture once and for all, so that for a large family of recurrences solving them takes a few seconds of comparison. This lesson states it in a general form, explains why it holds and works through examples, each checked numerically.

The Divide-and-Conquer Recurrences lesson gives the simple version for f(n)=Θ(nk)f(n) = \Theta(n^k). The version here also handles logarithmic factors and spells out the conditions that the simple version hides.

The watershed function

Fix constants a≥1a \ge 1 and b>1b > 1, and a function f(n)f(n) that is positive for large nn. In the recursion tree of

T(n)=aT(n/b)+f(n)T(n) = aT(n/b) + f(n)

the bottom level has alog⁡bn=nlog⁡baa^{\log_b n} = n^{\log_b a} leaves. The function nlog⁡ban^{\log_b a} is called the watershed function: it is the total cost of the leaves, and the whole theorem is a comparison between f(n)f(n), the cost of the root, and this watershed. The exponent log⁡ba\log_b a is the critical exponent.

Recurrence aa bb watershed nlog⁡ban^{\log_b a}
2T(n/2)+n2T(n/2) + n 2 2 nn
9T(n/3)+n9T(n/3) + n 9 3 n2n^2
T(2n/3)+1T(2n/3) + 1 1 3/23/2 n0=1n^0 = 1
7T(n/2)+n27T(n/2) + n^2 7 2 nlg⁡7≈n2.807n^{\lg 7} \approx n^{2.807}

The statement

Master theorem. Let a≥1a \ge 1 and b>1b > 1 be constants, let f(n)f(n) be asymptotically positive, and let T(n)=aT(n/b)+f(n)T(n) = aT(n/b) + f(n) for large nn, with n/bn/b read as either ⌊n/b⌋\lfloor n/b \rfloor or ⌈n/b⌉\lceil n/b \rceil and TT constant on small inputs. Then:

  1. If f(n)=O(nlog⁡ba−ϵ)f(n) = O(n^{\log_b a - \epsilon}) for some constant ϵ>0\epsilon > 0, then T(n)=Θ(nlog⁡ba)T(n) = \Theta(n^{\log_b a}).
  2. If f(n)=Θ(nlog⁡balg⁡kn)f(n) = \Theta(n^{\log_b a} \lg^k n) for some constant k≥0k \ge 0, then T(n)=Θ(nlog⁡balg⁡k+1n)T(n) = \Theta(n^{\log_b a} \lg^{k+1} n).
  3. If f(n)=Ω(nlog⁡ba+ϵ)f(n) = \Omega(n^{\log_b a + \epsilon}) for some constant ϵ>0\epsilon > 0, and af(n/b)≤cf(n)a f(n/b) \le c f(n) for some constant c<1c < 1 and all large nn, then T(n)=Θ(f(n))T(n) = \Theta(f(n)).

In terms of the tree:

  • Case 1, leaves win. ff is polynomially smaller than the watershed: the level costs grow geometrically going down, and the leaves dominate.
  • Case 2, a tie. ff matches the watershed up to a factor lg⁡kn\lg^k n. All about log⁡bn\log_b n levels contribute roughly equally, which adds one more factor of lg⁡n\lg n. With k=0k = 0 this is the familiar Θ(nlog⁡balg⁡n)\Theta(n^{\log_b a} \lg n).
  • Case 3, root wins. ff is polynomially larger, and the extra regularity condition af(n/b)≤cf(n)a f(n/b) \le c f(n) says the level costs really do shrink geometrically. Then the root dominates.

The word "polynomially" matters. In case 1, ff must be smaller by a factor nϵn^\epsilon, not merely smaller; a factor of lg⁡n\lg n is not enough. The gaps this leaves are the subject of When the Master Theorem Fails.

Proof sketch (exact powers of b)

For n=bmn = b^m the recursion tree gives exactly

T(n)=Θ(nlog⁡ba)+∑j=0log⁡bn−1ajf(n/bj),T(n) = \Theta(n^{\log_b a}) + \sum_{j=0}^{\log_b n - 1} a^j f(n/b^j),

the leaves plus the internal levels. Call the sum S(n)S(n).

  • Case 1. With f(x)≤Cxlog⁡ba−ϵf(x) \le C x^{\log_b a - \epsilon}, the term ajf(n/bj)a^j f(n/b^j) is at most Cnlog⁡ba−ϵ(bϵ)jC n^{\log_b a - \epsilon} (b^{\epsilon})^j, an increasing geometric series with ratio bϵ>1b^\epsilon > 1. Its sum is OO of its last term, which is O(nlog⁡ba)O(n^{\log_b a}).
  • Case 2. Each term is Θ(nlog⁡balg⁡k(n/bj))\Theta(n^{\log_b a} \lg^k (n/b^j)), and ∑jlg⁡k(n/bj)\sum_{j} \lg^k(n/b^j) over log⁡bn\log_b n levels is Θ(lg⁡k+1n)\Theta(\lg^{k+1} n) (it is a sum of kk-th powers of 1,2,…,log⁡bn1, 2, \ldots, \log_b n, up to the constant factor lg⁡kb\lg^k b).
  • Case 3. Regularity gives ajf(n/bj)≤cjf(n)a^j f(n/b^j) \le c^j f(n), a decreasing geometric series, so S(n)≤f(n)/(1−c)S(n) \le f(n)/(1 - c). Also S(n)≥f(n)S(n) \ge f(n) and ff dominates the leaves.

Handling floors and ceilings adds technical work but changes nothing.

Using it: a recipe

  1. Read off aa, bb and f(n)f(n), and compute the critical exponent log⁡ba\log_b a.
  2. Compare f(n)f(n) with nlog⁡ban^{\log_b a}. Is the ratio f(n)/nlog⁡baf(n)/n^{\log_b a} a negative power of nn, a power of lg⁡n\lg n, or a positive power of nn?
  3. In case 3, check regularity. For f(n)=npf(n) = n^p with p>log⁡bap > \log_b a it always holds: a(n/b)p=(a/bp) npa(n/b)^p = (a/b^p)\,n^p, and a/bp<1a/b^p < 1 exactly because p>log⁡bap > \log_b a.

The program applies the recipe to functions of the form f(n)=nplg⁡knf(n) = n^p \lg^k n, which cover most algorithms in practice.

python · try it yourself
import math

def term(p, k):
    """Write n^p lg^k n the way a person would."""
    parts = []
    if abs(p) > 1e-12:
        parts.append("n" if abs(p - 1) < 1e-12 else f"n^{p:.3g}")
    if k:
        parts.append("lg n" if k == 1 else f"lg^{k} n")
    return " ".join(parts) or "1"

def master(a, b, p, k=0):
    """Solve T(n) = a T(n/b) + n^p lg^k n with k >= 0."""
    e = math.log(a, b)                       # critical exponent log_b a
    if abs(p - e) < 1e-12:
        return "case 2: Theta(" + term(e, k + 1) + ")"
    if p < e:
        return "case 1: Theta(" + term(e, 0) + ")"
    return "case 3: Theta(" + term(p, k) + ")"   # regularity holds for these f

examples = [
    ("binary search    T(n/2) + 1",       1, 2,   0,   0),
    ("merge sort      2T(n/2) + n",       2, 2,   1,   0),
    ("                9T(n/3) + n",       9, 3,   1,   0),
    ("                T(2n/3) + 1",       1, 1.5, 0,   0),
    ("               2T(n/4) + sqrt n",   2, 4,   0.5, 0),
    ("               2T(n/2) + n lg n",   2, 2,   1,   1),
    ("              16T(n/4) + n^2",     16, 4,   2,   0),
    ("               4T(n/2) + n^3",      4, 2,   3,   0),
    ("Karatsuba      3T(n/2) + n",        3, 2,   1,   0),
    ("Strassen       7T(n/2) + n^2",      7, 2,   2,   0),
]
for name, a, b, p, k in examples:
    print(f"{name:34} -> {master(a, b, p, k)}")
binary search    T(n/2) + 1        -> case 2: Theta(lg n)
merge sort      2T(n/2) + n        -> case 2: Theta(n lg n)
                9T(n/3) + n        -> case 1: Theta(n^2)
                T(2n/3) + 1        -> case 2: Theta(lg n)
               2T(n/4) + sqrt n    -> case 2: Theta(n^0.5 lg n)
               2T(n/2) + n lg n    -> case 2: Theta(n lg^2 n)
              16T(n/4) + n^2       -> case 2: Theta(n^2 lg n)
               4T(n/2) + n^3       -> case 3: Theta(n^3)
Karatsuba      3T(n/2) + n         -> case 1: Theta(n^1.58)
Strassen       7T(n/2) + n^2       -> case 1: Theta(n^2.81)

Read a few lines carefully:

  • 9T(n/3)+n9T(n/3) + n: the watershed is nlog⁡39=n2n^{\log_3 9} = n^2, and f(n)=n=O(n2−1)f(n) = n = O(n^{2 - 1}), so case 1 with ϵ=1\epsilon = 1: Θ(n2)\Theta(n^2).
  • T(2n/3)+1T(2n/3) + 1: here b=3/2b = 3/2 and a=1a = 1, so the watershed is n0=1=f(n)n^0 = 1 = f(n). Case 2 with k=0k = 0 gives Θ(lg⁡n)\Theta(\lg n), like binary search. Nothing requires bb to be an integer.
  • 2T(n/4)+n2T(n/4) + \sqrt{n}: the watershed is nlog⁡42=n1/2n^{\log_4 2} = n^{1/2}, a tie, so Θ(nlg⁡n)\Theta(\sqrt{n} \lg n).
  • 2T(n/2)+nlg⁡n2T(n/2) + n \lg n: the watershed is nn, and f(n)=nlg⁡1nf(n) = n \lg^1 n, case 2 with k=1k = 1: Θ(nlg⁡2n)\Theta(n \lg^2 n). The simple version of the theorem, which only knows f(n)=npf(n) = n^p, cannot do this one.
  • 4T(n/2)+n34T(n/2) + n^3: the watershed is n2n^2, and f(n)=n3=Ω(n2+1)f(n) = n^3 = \Omega(n^{2 + 1}). Regularity: 4(n/2)3=n3/24(n/2)^3 = n^3/2, so c=1/2c = 1/2 works. Case 3: Θ(n3)\Theta(n^3).

Checking the answers numerically

A theorem is only as useful as your confidence in applying it. Compute each recurrence exactly at n=bmn = b^m with T(1)=1T(1) = 1 and divide by the predicted order of growth. If the prediction is right, the ratio settles towards a positive constant.

python · try it yourself
import math

def T(a, b, f, n):
    return 1 if n == 1 else a * T(a, b, f, n // b) + f(n)

lg = lambda n: n.bit_length() - 1          # exact lg for powers of 2
cases = [
    ("9T(n/3) + n",       9, 3, lambda n: n,            lambda n: n**2),
    ("2T(n/4) + sqrt n",  2, 4, lambda n: math.isqrt(n), lambda n: math.sqrt(n) * lg(n)),
    ("2T(n/2) + n lg n",  2, 2, lambda n: n * lg(n),     lambda n: n * lg(n)**2),
    ("16T(n/4) + n^2",   16, 4, lambda n: n * n,         lambda n: n * n * lg(n)),
    ("4T(n/2) + n^3",     4, 2, lambda n: n**3,          lambda n: n**3),
]
print("recurrence         ratio T(n) / prediction at n = b^4, b^8, b^12, b^16")
for name, a, b, f, g in cases:
    print(f"{name:18}", "  ".join(f"{T(a, b, f, b**m) / g(b**m):.4f}" for m in (4, 8, 12, 16)))
recurrence         ratio T(n) / prediction at n = b^4, b^8, b^12, b^16
9T(n/3) + n        1.4938  1.4999  1.5000  1.5000
2T(n/4) + sqrt n   0.6250  0.5625  0.5417  0.5312
2T(n/2) + n lg n   0.6875  0.5781  0.5486  0.5352
16T(n/4) + n^2     0.6250  0.5625  0.5417  0.5312
4T(n/2) + n^3      1.9375  1.9961  1.9998  2.0000

Every row levels off. Two converge quickly (to 3/23/2 and to 22); the three case-2 rows creep towards 1/21/2, because their exact solutions carry a lower-order term: for example 2T(n/2)+nlg⁡n2T(n/2) + n \lg n solves to exactly 12nlg⁡2n+12nlg⁡n+n\frac{1}{2} n \lg^2 n + \frac{1}{2} n \lg n + n. That slow drift is typical of case 2, and it is a reminder that Θ\Theta says nothing about how fast the ratio settles.

In practice: the master theorem only needs f(n)f(n) up to Θ\Theta. So "the merge costs Θ(n)\Theta(n)" is all the information required to conclude Θ(nlg⁡n)\Theta(n \lg n) for merge sort. The exact constants (14 comparisons for 7 elements, and so on) need the exact recurrence, as in Merge Sort.

Test yourself

What is the watershed function of T(n)=8T(n/2)+n2T(n) = 8T(n/2) + n^2, and which case applies?

  1. n2n^2, case 2
  2. n3n^3, case 1
  3. n8n^8, case 1
  4. n3n^3, case 3

Solve T(n)=3T(n/3)+nlg⁡2nT(n) = 3T(n/3) + n \lg^2 n with the master theorem.

  1. Θ(nlg⁡n)\Theta(n \lg n)
  2. Θ(nlg⁡2n)\Theta(n \lg^2 n)
  3. Θ(nlg⁡3n)\Theta(n \lg^3 n)
  4. The theorem does not apply

In case 3 with f(n)=npf(n) = n^p and p>log⁡bap > \log_b a, why does the regularity condition always hold?

  1. Because af(n/b)=(a/bp)f(n)a f(n/b) = (a/b^p) f(n) and a/bp<1a/b^p < 1
  2. Because ff is increasing
  3. Because b>1b > 1
  4. It does not always hold for polynomials

Which recurrence has the solution Θ(nlg⁡n)\Theta(\sqrt{n} \lg n)?

  1. T(n)=2T(n/4)+nT(n) = 2T(n/4) + \sqrt{n}
  2. T(n)=4T(n/2)+nT(n) = 4T(n/2) + \sqrt{n}
  3. T(n)=T(n/4)+nT(n) = T(n/4) + \sqrt{n}
  4. T(n)=2T(n/2)+nT(n) = 2T(n/2) + \sqrt{n}