Split a problem into smaller copies, solve them, combine. The number of copies sets the exponent. Strassen uses 7 block products instead of 8, so a 1024 by 1024 product needs 3.8 times fewer multiplications.
Pick a split rule, then drag the depth. Watch the tree fan out and the multiplication count climb. Then we build, piece by piece, the paradigm, four algorithms, and the three tools that turn any split rule into a running time.
You need recursion (a function that calls itself) and merge sort in outline. We build the rest from zero.
Follows Chapter 4 of Introduction to Algorithms by Cormen, Leiserson, Rivest and Stein (CLRS). The maximum subarray section is 4.1 of the third edition. The devices and toy inputs are our own.
Each split halves the size, so depth k means n = 2k (rows and columns for matrices, digits for numbers). The count assumes the recursion runs down to single entries or single digits. It ignores additions.
Chapter 0
Sort a stack of exams by halving it, and see where the savings come from
You must sort 1,024 exams by student ID. Insertion sort puts each exam into place, one at a time. In the worst case that takes 1,024 × 1,023 / 2 = 523,776 comparisons.
Merge sort splits the stack in half and sorts each half the same way. Then it merges the two sorted piles: compare the top exam of each pile and take the smaller. It needs fewer than 1,024 × 10 = 10,240 comparisons.
Merge sort is one case of divide and conquer: a method that solves a problem by solving smaller copies of it. It has three steps.
Blue rows split. Warm rows merge. Press Step and count how many items each level touches.
Illustrative: eight random numbers from 1 to 99.
Every merge level touches all n items once, so it costs about n. Halving reaches size 1 after lg n levels, where lg n is the logarithm base 2: how many times you can halve n. Eight items need 3 levels. So the total is about n lg n.
Why does splitting pay at all? Suppose the direct method costs n2. Two halves cost 2 × (n/2)2 = n2/2. For n = 1,024 that is 524,288 instead of 1,048,576. Each half then splits again and saves again.
Symptom: the recursion never stops and Python raises RecursionError.
Measure: print the size at each call. It must shrink every time.
Fix: return directly for size 0 and 1, and split as lo..mid and mid+1..hi with mid = (lo + hi) // 2, so both parts are smaller.
Chapter 1
Find the best run of days by splitting at the middle and scanning outward from it
A stock moved by −2, 1, −3, 4, −1, 2, 1, −5, 4 over nine days. You buy before one day and sell after a later day. Your profit is the sum of the changes in between. Which run of days pays most?
This is the maximum subarray problem: find the run of neighbouring cells with the largest sum. Trying every start and end checks about n2/2 runs.
Split at the middle index mid. The best run lies wholly left, wholly right, or across mid. The first two are recursive calls. The third is the combine step, and it has a short answer. Call the best sum of a run that ends at mid L, and the best sum of a run that starts at mid + 1 R.
C equals the max over i up to mid of S from i to mid, plus the max over j past mid of S from mid plus one to j.
Walk left from mid one cell at a time with a running sum, and keep the best: that is L. Walk right from mid + 1 the same way: that is R. C is L + R.
On the stock, mid = 4. Leftward sums from cell 4: −1, 3, 0, 1, −1, so L = 3 at cell 3. Rightward sums from cell 5: 2, 3, −2, 2, so R = 3 at cell 6. C = 6, the run [4, −1, 2, 1].
Press Step to extend the scan one cell. Then switch the crossing case off and see what the recursion reports.
The nine changes are the classic textbook example. Cells run from 0 to 8.
Each call splits again. The table runs the whole recursion. The left half of the top call is cells 0 to 4, so cell 4 belongs to it.
| Call | Best left | Best right | Crossing | Returns |
|---|---|---|---|---|
| A[0..8], mid 4 | 4, cells 3..3 | 4, cells 8..8 | 6, cells 3..6 | 6 |
| A[0..4], mid 2 | 1, cells 1..1 | 4, cells 3..3 | 2, cells 1..3 | 4 |
| A[5..8], mid 6 | 3, cells 5..6 | 4, cells 8..8 | 2, cells 5..8 | 4 |
| A[3..4], mid 3 | 4 | −1 | 3 | 4 |
| A[5..6], mid 5 | 2 | 1 | 3 | 3 |
The cost is two half-size calls plus a linear scan, the same as merge sort: n lg n. A one-pass method, Kadane's algorithm, takes n steps. It keeps the best run that ends at the current cell, and restarts when that sum drops below zero. The crossing idea still matters, because closest pair (Chapter 8) needs it.
Symptom: the code returns 4 on the stock, not 6.
Measure: compare it with brute force on 20 random arrays.
Fix: scan all the way to both ends of the call's range, not only the two cells next to mid.
Chapter 2
Trade one block multiplication for extra additions, and watch the exponent drop below 3
The schoolbook product of two n by n matrices fills n2 entries. Each entry is a row times a column: n multiplications. So it costs n3. For n = 1,024 that is about 1.07 billion multiplications.
Split each matrix into four (n/2) by (n/2) blocks. Then C11 = A11B11 + A12B21, and the other three blocks follow the same pattern. That is 8 block products. Recursing on 8 products gives back n3 exactly, so the split alone saves nothing.
In 1969 Volker Strassen found 7 products of sums and differences that rebuild all four blocks:
The grid holds every product AijBkl. Pick a block, then add its P terms one by one. Cells cancel until only the two true terms stay.
The running total uses the worked example below, A = [[1, 3], [7, 5]] and B = [[6, 8], [4, 2]], where each block is one number.
Seven products per split, repeated down to single entries, gives the count. Call the number of scalar multiplications for size n M(n).
M of n equals seven to the lg n, which equals n to the lg seven, about n to the 2.807.
Each halving multiplies the number of products by 7. After lg n halvings there are 7 to the lg n of them, each one a single multiplication. With 8 per split the same count is n3.
n = 1,024, so lg n = 10. M = 710 = 282,475,249, about 2.8 × 108. The schoolbook needs 810 = 1.07 × 109: 3.8 times more. At n = 4,096 it is 1.4 × 1010 against 6.9 × 1010: 5.0 times.
Check it on 2 by 2 numbers, where each block is one entry.
| Product | Arithmetic | Value |
|---|---|---|
| P1 | 1 × (8 − 2) | 6 |
| P2 | (1 + 3) × 2 | 8 |
| P3 | (7 + 5) × 6 | 72 |
| P4 | 5 × (4 − 6) | −10 |
| P5 | (1 + 5) × (6 + 2) | 48 |
| P6 | (3 − 5) × (4 + 2) | −12 |
| P7 | (1 − 7) × (6 + 8) | −84 |
Then C11 = 48 − 10 − 8 − 12 = 18, C12 = 14, C21 = 62 and C22 = 48 + 6 − 72 + 84 = 66. The schoolbook gives the same [[18, 14], [62, 66]].
Symptom: in floating point, Strassen's result drifts further from the true product than the schoolbook's.
Measure: compute the largest entry error against a double-precision reference for both methods.
Fix: stop recursing below a block size and use the schoolbook there. The subtractions are what lose digits.
Chapter 3
Get the middle term of a product from one multiplication, and take big numbers below n squared
Grade-school multiplication multiplies every digit of one number by every digit of the other. Two 4-digit numbers take 16 digit products. Two n-digit numbers take n2.
Split each number into a high half and a low half of m digits: 1234 = 12 × 100 + 34. Write the halves of x as x1 and x0, and of y as y1 and y0. The product needs x1y1, x0y0 and the middle term x1y0 + x0y1. Four half-size products give back n2.
Anatolii Karatsuba saw in 1960 that the middle term is one sum, so it needs one product. Call the high product z2 = x1y1 and the low product z0 = x0y0.
z-one equals x-one plus x-zero, times y-one plus y-zero, minus z-two, minus z-zero.
Multiply the two sums once. That product holds all four cross terms. Subtract z2 and z0, and the middle term z1 is left. Then x times y is z2 shifted 2m places, plus z1 shifted m places, plus z0.
1234 × 5678: z2 = 12 × 56 = 672 and z0 = 34 × 78 = 2,652. Then 46 × 134 = 6,164, so z1 = 6,164 − 672 − 2,652 = 2,840. Result: 6,720,000 + 284,000 + 2,652 = 7,006,652.
Pick a pair to see the three products and the assembly. Drag the digit length to compare the work at scale.
The bars count single-digit multiplications when the recursion runs down to one digit. Additions and carries are not counted.
Three half-size products per split give 3lg n = nlg 3 ≈ n1.585 digit products. For 1,024 digits that is ten halvings: 310 = 59,049 against 410 = 1,048,576, about 18 times fewer.
Symptom: Karatsuba is slower than the grade-school method on small numbers.
Measure: time both over a range of sizes and find where the curves cross.
Fix: use the grade-school method below that size. Big-number libraries pick the switch point by timing.
Chapter 4
Write the running time as an equation about itself, then prove a guess by induction
Every algorithm so far has the same shape. It makes some smaller calls of equal size and does some work outside them. A recurrence writes that shape as an equation: the time for size n from the time for smaller sizes. Call the number of calls a, the shrink factor b, and the outside work f(n).
T of n equals a times T of n over b, plus f of n.
To cost one call, cost its a smaller calls of size n/b and add the f(n) work it does itself.
Merge sort: a = 2, b = 2, f(n) = n. Strassen: a = 7, b = 2, f(n) = n2 for the block additions. Karatsuba: a = 3, b = 2, f(n) = n. Binary search: a = 1, b = 2, f(n) = 1.
The substitution method solves a recurrence in two steps: guess a bound, then prove it by induction. Take T(n) = 2T(n/2) + n with T(1) = 1, and guess T(n) ≤ c n lg n. Assume the guess holds for n/2 and put it into the right side.
Two times c times n over two times lg of n over two, plus n, equals c n lg n, minus c minus one, times n.
lg(n/2) is lg n minus 1, so the two halves give c n lg n minus c n. Adding the merge n leaves c n lg n minus (c − 1) n. That is at most c n lg n whenever c is at least 1.
c = 2, n = 8: 2 × 2 × 4 × 2 + 8 = 40, and c n lg n = 48. The true T(8) is 32, below both.
The induction step wants c ≥ 1. The base case wants more. With c = 1 the bound at n = 2 is 1 × 2 × 1 = 2, but T(2) = 2T(1) + 2 = 4. So choose c = 2: T(2) = 4 ≤ 4. The bound then holds for every n ≥ 2. Big-O allows a starting size n0, so n = 1 may fail.
Teal dots are the exact T(n). The warm curve is c n lg n. Drag c until no dot sits above the curve from n = 2 on.
T(n) = T(⌊n/2⌋) + T(⌈n/2⌉) + n with T(1) = 1, computed exactly for n = 2 to 64.
Symptom: you try T(n) ≤ c n and get T(n) ≤ c n + n.
Measure: check whether the same constant c comes back. Here it cannot, for any c.
Fix: the guess is too small. Try the next size up, c n lg n.
Chapter 5
Draw every call as a node, sum each level, and read the total from one ratio
Substitution needs a guess. A recursion tree makes one. Draw each call as a node and write the work it does outside its children. Then add up each level. Take f(n) = c nd, a power of n.
At depth k there are ak nodes. Each works on size n/bk. Call the total work at depth k Wk.
W-k equals a to the k, times c times n over b to the k, all to the d, which equals c n to the d times r to the k, where r is a over b to the d.
Going down one level multiplies the node count by a and divides each node's work by bd. So each level costs r times the level above. The total is a geometric series with ratio r.
T(n) = 3T(n/4) + n2: r = 3/16 = 0.1875. The levels cost n2, 0.19n2, 0.035n2 and so on. The sum stays below n2 × 16/13 ≈ 1.23n2, so T(n) = Θ(n2).
The ratio decides the shape. If r < 1 the root level wins and T = Θ(nd). If r = 1 every level costs the same, and lg n levels give Θ(nd lg n). If r > 1 the leaves win. There are alogb n = nlogb a of them, so T = Θ(nlogb a).
Each bar is one level's total work for n = 4,096. Pick a recurrence and watch whether the bars shrink, stay level or grow.
Work per node is (size)d with c = 1. Bars share one scale inside each recurrence. On a phone the labels read depth · nodes.
Trees also handle uneven splits. In T(n) = T(n/3) + T(2n/3) + n every full level costs n. The tree is between log3 n and log3/2 n levels deep, so T = Θ(n lg n).
Symptom: you predict Θ(n) for 4T(n/2) + n because the root costs n.
Measure: count the leaves: 4lg n = n2. At n = 1,024 that is 1,048,576.
Fix: always add the leaf level. When r > 1 it is the biggest term.
Chapter 6
Read the running time of a recurrence from a, b and the combine exponent alone
The tree gives a rule you can apply without drawing. Compare the combine exponent d with the critical exponent logb a, the exponent of the leaf count.
T of n is theta of n to the d if d beats log base b of a, n to the d lg n on a tie, and n to the log base b of a if d loses.
Work out logb a. If d is bigger, the root wins and T is nd. If they tie, every level costs nd and you pay it lg n times. If d is smaller, the leaves win.
Strassen: a = 7, b = 2, d = 2. log2 7 = 2.807 > 2, so T = Θ(n2.807). Merge sort: log2 2 = 1 = d, so Θ(n lg n). 3T(n/4) + n2: log4 3 = 0.79 < 2, so Θ(n2).
Purple marks logb a. Warm marks d. Drag the three sliders and watch which mark is further right.
This is the form for f(n) = nd. The general theorem compares any f(n) with nlogb a.
The general theorem compares f(n) with nlogb a and needs a gap of a power of n. Its third case also needs a regularity condition: a·f(n/b) ≤ c·f(n) for some c < 1. For f(n) = nd that is r < 1, which holds whenever d wins.
T(n) = 2T(n/2) + n lg n beats n1 only by a log factor. The basic three cases do not cover it. The extended second case in the fourth edition of CLRS does: it gives Θ(n lg2 n).
Symptom: the theorem gives an answer for T(n) = T(n/3) + T(2n/3) + n, or for T(n) = n·T(n/2) + n.
Measure: check the form: equal part sizes, a constant a ≥ 1, a constant b > 1.
Fix: use a recursion tree, or the Akra–Bazzi method for unequal parts.
Chapter 7
Make the merge step report how unsorted the array was, at no extra cost
Two people rank the same six films. How different are their lists? Write one list in the order of the other and count the pairs that are out of order.
An inversion is a pair of positions i < j with A[i] > A[j]. A sorted array has none. A reversed array of n items has n(n − 1)/2, the most possible. Checking every pair costs n2/2.
Merge sort can count them while it merges. Say the merge takes an item from the right half while i items of the left half are already used. Every left item still waiting is larger, and it came earlier in the array. So each waiting item makes one inversion with the item just taken. Add len(left) − i.
Teal is the left half, blue the right. Press Step. When a right item wins, the left items it jumps flash warm and the tally rises by that many.
The halves are the top-level merge only. The calls below counted the inversions inside each half.
With L = [2, 5, 8] and R = [1, 4, 7], taking 1 jumps 3 waiting items, taking 4 jumps 2, and taking 7 jumps 1. The merge finds 6 split inversions in one pass, where checking pairs looks at 15.
The total is the inversions inside the left half, plus those inside the right half, plus the split ones. The recurrence is 2T(n/2) + n, so counting costs n lg n.
Symptom: the count is too high on arrays with repeated values.
Measure: compare with brute-force pair counting on arrays with duplicates.
Fix: on a tie, take from the left (<=). A tie is not an inversion. The same rule keeps merge sort stable.
Chapter 8
Split the plane, solve each side, and check only a thin strip along the line
A map holds n delivery drones. Which two are closest? Measuring every pair takes n(n − 1)/2 distances: 499,500 for 1,000 drones.
Why only a few? Look at a δ by 2δ box that starts at a strip point and goes up. Cut it into eight squares of side δ/2. Two points in one square would be at most δ/√2 ≈ 0.71δ apart, closer than δ, on the same side. That is impossible. So the box holds at most 8 points: each strip point needs at most 7 comparisons.
Press Play or Step. Blue is the split line, warm the strip of width 2δ, teal the best pair so far. Then add points and compare the counts.
Illustrative random points. Halves of 3 or fewer points use brute force. The count includes those base-case pairs and every strip comparison.
If the strip is re-sorted by y at every level, the combine costs n lg n and the total is n lg2 n. Instead, keep one list sorted by y from the start and split it alongside. Then the combine is linear, the recurrence is 2T(n/2) + n, and the total is n lg n.
Symptom: on some inputs the answer is a little too far apart.
Measure: compare with brute force on a few hundred random point sets.
Fix: build the strip with δ = min(δL, δR), and sort it by y before you compare neighbours.
Chapter 9
Keep the recurrences, the numbers, the checks and the code in one place
Every algorithm here is a choice of a, b and f(n). Fewer subproblems lower the exponent. A cheap combine keeps the levels light. The master theorem turns the three numbers into a running time.
| Algorithm | Recurrence | Time | Number to remember |
|---|---|---|---|
| Merge sort | 2T(n/2) + n | n lg n | 1,024 items: under 10,240 comparisons |
| Binary search | T(n/2) + 1 | lg n | 1,024 items: 11 probes at most |
| Maximum subarray | 2T(n/2) + n | n lg n | the stock: [4, −1, 2, 1], sum 6 |
| Strassen | 7T(n/2) + n² | n2.807 | n = 1,024: 3.8 times fewer products |
| Karatsuba | 3T(n/2) + n | n1.585 | 1,024 digits: about 18 times fewer |
| Count inversions | 2T(n/2) + n | n lg n | [2,5,8] + [1,4,7]: 6 split inversions |
| Closest pair | 2T(n/2) + n | n lg n | at most 7 strip comparisons per point |
| Quickselect, average | T(n/2) + n | n | one side only: n + n/2 + ... < 2n |
pythonimport math def master(a, b, d): # T(n) = a T(n/b) + n^d crit = math.log(a, b) # critical exponent if abs(d - crit) < 1e-9: return f"n^{d} lg n" # tie: every level equal if d > crit: return f"n^{d}" # root wins return f"n^{crit:.3f}" # leaves win def kadane(A): # maximum subarray in one pass best, here = A[0], 0 for x in A: here = max(x, here + x) # extend the run, or restart at x best = max(best, here) return best def karatsuba(x, y): if x < 10 or y < 10: return x * y m = max(len(str(x)), len(str(y))) // 2 x1, x0 = divmod(x, 10 ** m); y1, y0 = divmod(y, 10 ** m) z2, z0 = karatsuba(x1, y1), karatsuba(x0, y0) z1 = karatsuba(x1 + x0, y1 + y0) - z2 - z0 # three products, not four return z2 * 10 ** (2 * m) + z1 * 10 ** m + z0 master(7, 2, 2) # 'n^2.807' Strassen master(2, 2, 1) # 'n^1 lg n' merge sort kadane([-2, 1, -3, 4, -1, 2, 1, -5, 4]) # 6 karatsuba(1234, 5678) # 7006652
Now press Present or Teach and explain from memory: the three steps, the crossing scan, Strassen's count, the level ratio r and the three cases. Then go back to the hero, switch between 8 and 7 products at depth 10, and say why the gap is 3.8 times.