Teaches how to measure an algorithm's cost with recurrences. Every later topic is judged with these tools.
Open the interactive lessons →Divide and Conquer & Recurrences past questions
Contents
- What divide and conquer means
- Turning code into a recurrence
- Solving a recurrence with the recursion tree
- The master theorem: solve recurrences in seconds
- Counting inversions
- Quick Select: find the $k$-th smallest without sorting
- Median of Medians: a pivot you can trust
- Closest pair of points
- Multiplying large numbers: Karatsuba
1. What divide and conquer means
Cut the job into smaller copies of itself, let recursion do the copies, then glue the results.
The strategy: split a problem, solve the pieces by recursion, combine the answers.
The question this lesson answers. How can a large problem be solved by solving smaller copies of it?
| New word | Meaning |
|---|---|
| subproblem | a smaller copy of the same problem |
| base case | an input so small that it is answered directly |
| combine | the work that joins the answers of the parts |
Imagine you must find the smallest mark in a pile of 1,000 answer sheets. You could scan all 1,000. Or you could give 500 to a friend and keep 500, each of you reports a smallest, and you pick the smaller of the two reports. Your friend may split their pile again. That is divide and conquer.
Splitting a pile among helpers who split it further. It breaks down where helpers need to talk a lot: if gluing the reports back together is slow, splitting does not help. That glue step is the combine cost, and we will count it carefully.
Divide and conquer has three steps. Divide: split the problem into smaller problems of the same kind. Conquer: solve each smaller problem by calling the same function (recursion); stop at a base case. Combine: join the small answers into the answer to the big problem.
Why it works. Recursion handles the copies for you, so you only design two things: how to split and how to combine.
Here is the exact code that appears in the PYQs (Dec 2023 and Mar 2025). Read it line by line.
Python
def find_min(L, low, high):
if low == high:
return L[low]
mid = (low + high) // 2
min1 = find_min(L, low, mid)
min2 = find_min(L, mid + 1, high)
return min(min1, min2)
Full trace for L = [8, 3, 6, 5, 9, 2, 7, 4] (calls listed in the order they start)
| # | call | mid | base case? | result |
|---|---|---|---|---|
| 1 | find_min(L, 0, 7) | 3 | False | min(3, 2) = 2 |
| 2 | find_min(L, 0, 3) | 1 | False | min(3, 5) = 3 |
| 3 | find_min(L, 0, 1) | 0 | False | min(8, 3) = 3 |
| 4 | find_min(L, 0, 0) | - | True | returns L[0] = 8 |
| 5 | find_min(L, 1, 1) | - | True | returns L[1] = 3 |
| 6 | find_min(L, 2, 3) | 2 | False | min(6, 5) = 5 |
| 7 | find_min(L, 2, 2) | - | True | returns L[2] = 6 |
| 8 | find_min(L, 3, 3) | - | True | returns L[3] = 5 |
| 9 | find_min(L, 4, 7) | 5 | False | min(2, 4) = 2 |
| 10 | find_min(L, 4, 5) | 4 | False | min(9, 2) = 2 |
| 11 | find_min(L, 4, 4) | - | True | returns L[4] = 9 |
| 12 | find_min(L, 5, 5) | - | True | returns L[5] = 2 |
| 13 | find_min(L, 6, 7) | 6 | False | min(7, 4) = 4 |
| 14 | find_min(L, 6, 6) | - | True | returns L[6] = 7 |
| 15 | find_min(L, 7, 7) | - | True | returns L[7] = 4 |
Each step down the tree doubles the number of calls and halves their size. The work in one call is tiny here (one min). This is the picture we will use to measure cost.
Worked example: Count the calls for n = 16
Problem.
How many times is find_min called on a list of 16 numbers?
Idea.
Add up calls per level of the tree.
- Level 0 has 1 call, level 1 has 2, level 2 has 4, level 3 has 8, level 4 has 16.
- Sum: $1+2+4+8+16=31$.
- Check with the doubling-sum rule: $2^5-1=31$.
Answer.
31 calls, which is $2n-1$ for $n=16$.
Common mistake.
Counting only the leaves (16) and forgetting the calls above them.
$T(n)$ counts steps, not seconds. We do not care whether one step is 1 nanosecond or 5. We care how the number of steps grows when $n$ grows.
Analogy and its limit. Splitting the shelves between two friends is divide and conquer. Limit: in real life the friends work at the same time, so the clock time is short. In the recurrence $T(n)$ we count total operations, not clock time. Doing the pieces one after the other costs the same $T(n)$ in the exam.
| Strategy | Pieces | Pieces solved | Example | Cost shape |
|---|---|---|---|---|
| Brute force | none | all pairs / all options | check every pair of points | often $n^2$ |
| Divide and conquer (many pieces) | $a\ge2$ | all $a$ pieces | find_min, merge sort, closest pair | $aT(n/b)+f(n)$ |
| Decrease and conquer (one piece) | 1 | only one piece, the rest thrown away | binary search, Quick Select | $T(n/2)+f(n)$ or $T(n-1)+f(n)$ |
| Subtract one | 1 (of size $n-1$) | 1 | sum a list recursively | $T(n-1)+O(1)$ is $O(n)$ |
Worked example: Sum a list by halving
Problem.
Write a divide-and-conquer function that sums a list of $n$ numbers and give its recurrence.
Idea.
Three questions: calls, size, extra work.
- Split the list in two halves, sum each (2 calls of size $n/2$).
- Combine with one addition: extra work 1.
- $T(n)=2T(n/2)+1$. $a=2$, $b^d=2^0=1$: $a>b^d$, so $O(n^{\log_2 2})=O(n)$.
- Exact count: $T(n)=2n-1$ calls, the same tree as
find_min.
Answer.
$O(n)$
Common mistake.
Calling it $O(\log n)$ because "we halve". Both halves are processed, so every element is touched.
| Common mistake | Why it feels right | Correction |
|---|---|---|
| "Halving means $O(\log n)$" | binary search halves | Only if one half is kept. If both halves are solved the cost is at least linear. |
| "Every D&C is $n\log n$" | merge sort is the famous example | It depends on the extra work and the number of pieces: find_min is $O(n)$. |
| Counting the base case as free | it looks tiny | There are about $n$ base cases; they add up. |
Worked example: One missing + 1
Problem.
In find_min, the second call is changed to find_min(L, mid, high). What happens for a list of two numbers?
Idea.
Check that every call works on a smaller range.
- With
low = 0andhigh = 1,midis 0. - The second call is
find_min(L, 0, 1), the same range again. - The base case is never reached for that call.
Answer.
The recursion never ends and Python raises RecursionError.
Common mistake.
Checking only the first recursive call and assuming both shrink.
- Read two numbers from the code: how many recursive calls, and the size given to each. They are $a$ and $b$.
- Whatever the function does outside its recursive calls is the combine cost.
- Find the base case before tracing, so you know where the recursion stops.
Divide, recurse, combine.
| Step | Method for any exam question |
|---|---|
| 1 | Check for the base case. |
| 2 | Split into smaller copies. |
| 3 | Solve the copies by recursion. |
| 4 | Combine their answers. |
2. Turning code into a recurrence
Count: how many recursive calls, how big each one is, and how much extra work happens outside the calls.
How to write the cost $T(n)$ of a recursive function as an equation (a recurrence).
The question this lesson answers. Given code, how do you write the equation for its running time?
| New word | Meaning |
|---|---|
| recurrence | a formula for the running time that uses the running time of smaller inputs |
| $a$ | the number of recursive calls |
| $n/b$ | the size given to each call |
Counting the work of a family tree: note how many children each person has, how much smaller each child's job is, and what the parent does personally.
A recurrence is an equation that gives the cost of a problem of size $n$ using the cost of smaller problems. You always build it by answering three questions about the code.
1. How many recursive calls are executed? Call it $a$. 2. How big is each call? Size $n/b$ (halved) or $n-1$ (one removed). 3. How much extra work is done outside the calls (loops, slicing, min, merging)? Call it $f(n)$. Then $T(n)=a\,T(\text{size})+f(n)$.
Why it works. The time of one call is the time of the calls it makes plus the work it does itself, which is exactly what a recurrence says.
Apply the recipe to find_min from the last section.
| Question | Answer for find_min | Where in the code |
|---|---|---|
| How many calls? | $a=2$ | lines 5 and 6 |
| How big is each? | about $n/2$ | low..mid and mid+1..high |
| Extra work? | $O(1)$: one min, one // | line 4 and line 7 |
$T(n)=2T(n/2)+1$: two calls run, each on half, with one comparison outside them. A wrong option changes one of those three parts.
Binary search (for comparison)
def binary_search(L, x, low, high):
if low > high:
return -1
mid = (low + high) // 2
if L[mid] == x:
return mid
if x < L[mid]:
return binary_search(L, x, low, mid - 1)
return binary_search(L, x, mid + 1, high)
Binary search has two recursive calls written, but only one runs each time. So $a=1$, giving $T(n)=T(n/2)+O(1)$. find_min runs both calls, so $a=2$. Count calls that are executed, not calls that are written.
| Code idea | $a$ | size | extra work | Recurrence |
|---|---|---|---|---|
| find_min | 2 | $n/2$ | 1 | $T(n)=2T(n/2)+1$ |
| binary search | 1 | $n/2$ | 1 | $T(n)=T(n/2)+1$ |
| max_subarray_sum (Aug 2023) | 2 | $n/2$ | $n$ (crossing loop) | $T(n)=2T(n/2)+n$ |
| merge sort | 2 | $n/2$ | $n$ (merge) | $T(n)=2T(n/2)+n$ |
sum a list by L[0]+f(L[1:]) | 1 | $n-1$ | $n$ (slicing copies) | $T(n)=T(n-1)+n$ |
| recursion that just peels one item | 1 | $n-1$ | 1 | $T(n)=T(n-1)+1$ |
The O(n) part of "largest sum of a contiguous block"
def max_crossing_sum(A, low, mid, high): # halves are A[low:mid] and A[mid:high]
left = total = A[mid - 1]
for i in range(mid - 2, low - 1, -1): # best block ENDING at the border
total += A[i]
left = max(left, total)
right = total = A[mid]
for j in range(mid + 1, high): # best block STARTING at the border
total += A[j]
right = max(right, total)
return left + right
def max_block(A, low, high): # call as max_block(A, 0, len(A))
if high - low == 1: # base case: one element
return A[low]
mid = (low + high) // 2
return max(max_block(A, low, mid),
max_block(A, mid, high),
max_crossing_sum(A, low, mid, high))
In max_block above, the two recursive calls on (low, mid) and (mid, high) give $a=2$ and size $n/2$. The function max_crossing_sum has two for loops that together visit every position from low to high once, so its cost is $O(n)$. That gives $T(n)=2T(n/2)+O(n)$.
Worked example: Divide into 7 pieces
Problem.
A strategy divides a problem of size $n$ into 7 subproblems of size $n/7$. Dividing costs $O(n)$. Combining costs $3n+5$ steps. Write the recurrence.
Idea.
Add the divide cost and the combine cost to get $f(n)$.
- $a=7$ calls, each of size $n/7$.
- Extra work = divide $+$ combine $=O(n)+(3n+5)$.
- $O(n)+3n+5$ is still $O(n)$: constant factors and the lower-order $5$ are dropped.
- So $T(n)=7T(n/7)+O(n)$.
Answer.
$T(n)=7T(n/7)+O(n)$
Common mistake.
Forgetting the divide cost, or thinking the "+5" changes the growth.
Check the recurrence against real counts
| $n$ | $T(n)$ for $T(n)=2T(n/2)+1$, $T(1)=1$ | $2n-1$ |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 3 | 3 |
| 4 | 7 | 7 |
| 8 | 15 | 15 |
| 16 | 31 | 31 |
| 32 | 63 | 63 |
Exam move. For "which recurrence represents this code": find the recursive calls, count how many actually run, read their sizes, then read the extra work. Eliminate options that disagree on any one of the three.
Unfamiliar patterns: what hides extra work? Exam code often looks short but hides a loop. Learn the five hiding places. This table is new teaching, not a PYQ.
| What you see in the code | Hidden extra work | Recurrence |
|---|---|---|
two calls on halves + min(a, b) | $O(1)$ | $2T(n/2)+O(1)$ |
two calls on halves + a for loop over the range | $O(n)$ | $2T(n/2)+O(n)$ |
two calls on L[:mid] and L[mid:] and nothing else | slicing copies the list: $O(n)$ | $2T(n/2)+O(n)$ |
one call on half + one for loop | $O(n)$ | $T(n/2)+O(n)$ |
one call with size $n-1$ + a for loop | $O(n)$ | $T(n-1)+O(n)$ |
| one call with size $n-1$ + constant work | $O(1)$ | $T(n-1)+O(1)$ |
| three calls on halves + linear work | $O(n)$ | $3T(n/2)+O(n)$ |
Short code, hidden linear work
def f(L):
if len(L) <= 1: return
f(L[:len(L)//2])
f(L[len(L)//2:])
Slicing L[a:b] copies the elements, so it costs $O(b-a)$, not $O(1)$. A function that only slices and recurses is still $2T(n/2)+O(n)$. Passing low and high indices (as in find_min) avoids the copy.
Method in four lines: (1) how many recursive calls actually run; (2) how big is each call (halved? minus one?); (3) what extra work besides the calls (loops, slicing, one min); (4) write $T(n)=aT(\text{size})+\text{extra}$.
Worked example: Read the code, write the recurrence
Problem.
def g(L): if len(L)<=1: return 0; m=len(L)//2; return g(L[:m]) + g(L[m:]) + sum(L)
Idea.
Calls, size, extra work.
- Two calls, each of size $n/2$.
- Extra work:
sum(L)is one pass, $O(n)$, plus the slicing copies, also $O(n)$. - $T(n)=2T(n/2)+O(n)$ ($a=b^d=2$): $O(n\log n)$.
Answer.
$O(n\log n)$
Common mistake.
Missing the work of sum(L) and the slices.
Worked example: A loop does not mean $n\log n$
Problem.
f(n) loops $n$ times and then calls f(n // 2) once, stopping at $n=1$ after one step. How much work is done for $n=1024$?
Idea.
Add the work of each level; there is one call per level.
- The levels cost $1024, 512, 256, \dots, 1$.
- This halving sum equals $2\cdot1024-1$.
Answer.
$2047$ steps, which is $O(n)$.
Common mistake.
Multiplying $n$ by the number of levels.
Calls, size, extra work.
| Step | Method for any exam question |
|---|---|
| 1 | Count the recursive calls. |
| 2 | Find the size passed to each. |
| 3 | Add up the work outside the calls. |
| 4 | State the base case. |
3. Solving a recurrence with the recursion tree
Draw the calls as a tree, find the cost of each level, add the levels.
How to turn a recurrence into a plain growth rate by adding up the work level by level.
The question this lesson answers. How do you add up the work of all the recursive calls?
| New word | Meaning |
|---|---|
| recursion tree | a drawing with one node for each call |
| level | all calls at the same depth |
| depth | the number of times the size is divided before reaching the base case |
A company chart. Add up the work done on each floor, then add the floors.
Take $T(n)=2T(n/2)+n$. Draw it as a tree. The top call does $n$ steps of its own work. It makes 2 calls of size $n/2$, each doing $n/2$ steps of its own work, and so on.
At level $i$: there are $a^i$ calls, each of size $n/b^i$. The work at level $i$ is $a^i\cdot f\!\left(n/b^i\right)$. Add up all levels.
Why it works. Grouping calls by level turns a branching process into one sum, one term for each level.
T(n) = 2T(n/2) + n with n = 64
| level $i$ | calls $2^i$ | size $n/2^i$ | work per call | work at this level |
|---|---|---|---|---|
| 0 | 1 | 64 | 64 | 64 |
| 1 | 2 | 32 | 32 | 64 |
| 2 | 4 | 16 | 16 | 64 |
| 3 | 8 | 8 | 8 | 64 |
| 4 | 16 | 4 | 4 | 64 |
| 5 | 32 | 2 | 2 | 64 |
| 6 | 64 | 1 | 1 | 64 |
T(n) = 4T(n/2) + n with n = 64
| level $i$ | calls $4^i$ | size $n/2^i$ | work per call | work at this level |
|---|---|---|---|---|
| 0 | 1 | 64 | 64 | 64 |
| 1 | 4 | 32 | 32 | 128 |
| 2 | 16 | 16 | 16 | 256 |
| 3 | 64 | 8 | 8 | 512 |
| 4 | 256 | 4 | 4 | 1024 |
| 5 | 1024 | 2 | 2 | 2048 |
| 6 | 4096 | 1 | 1 | 4096 |
T(n) = 2T(n/8) + n with n = 512 (a = 2, b = 8)
| level $i$ | calls $2^i$ | size $n/8^i$ | work per call | work at this level |
|---|---|---|---|---|
| 0 | 1 | 512 | 512 | 512 |
| 1 | 2 | 64 | 64 | 128 |
| 2 | 4 | 8 | 8 | 32 |
| 3 | 8 | 1 | 1 | 8 |
T(n) = T(n-1) + n with n = 8 (subtract type, not halving)
| step | size | work |
|---|---|---|
| 0 | 8 | 8 |
| 1 | 7 | 7 |
| 2 | 6 | 6 |
| 3 | 5 | 5 |
| 4 | 4 | 4 |
| 5 | 3 | 3 |
| 6 | 2 | 2 |
| 7 | 1 | 1 |
Every recurrence falls in one of three shapes: levels equal (multiply by $\log n$), levels growing (the bottom wins), levels shrinking (the top wins). The master theorem is just a quick way to say which shape you have.
Equal levels: $c+c+\dots+c$ = (number of levels) × $c$.
Halving going down: $n+\frac n2+\frac n4+\dots$ Picture a bar of length $2n$: the first term fills half of it and each later term fills half of what is still empty, so the sum stays below $2n$. The top level decides.
Doubling going down: $1+2+4+8=15=2\cdot 8-1$. All earlier terms together are smaller than the last one, so the sum is below twice the last term. The bottom level decides.
The same holds for any fixed ratio other than 1; only the constant (here 2) changes.
Do not add the cost of one level and forget the number of levels. $2T(n/2)+n$ is $n\log n$ because each of the $\log n$ levels costs $n$, not because one level costs $n\log n$.
Worked example: Add the levels yourself
Problem.
Find the growth of $T(n)=T(n/2)+n$ with $T(1)=1$.
Idea.
One call per level, with half the size, doing work equal to its size.
- Level 0 work: $n$. Level 1: $n/2$. Level 2: $n/4$. …
- The levels shrink by half each time.
- Sum $=n(1+\tfrac12+\tfrac14+\dots)<2n$.
Answer.
$O(n)$. The root dominates.
Common mistake.
Saying $O(n\log n)$ because there are $\log n$ levels. The levels do not all cost $n$ here.
Why does the master rule have exactly three cases? Derivation from the tree. Level $i$ has $a^i$ calls, each of size $n/b^i$, each doing $(n/b^i)^d$ work. So level $i$ costs
$a^i\left(\dfrac{n}{b^i}\right)^d=n^d\left(\dfrac{a}{b^d}\right)^i$. Let $r=\dfrac{a}{b^d}$. The levels form a geometric series $n^d(1+r+r^2+\dots+r^{k})$ with $k=\log_b n$ levels.
| Ratio $r=a/b^d$ | Series behaves like | Which level dominates | Total | Same as exam rule |
|---|---|---|---|---|
| $r<1$ ($a<b^d$) | $1+r+r^2+\dots$ shrinks; sum $\le \frac1{1-r}$, a constant | the root (top level) | $n^d$ | $a<b^d$: $O(n^d)$ |
| $r=1$ ($a=b^d$) | every term equals 1; there are $\log_b n+1$ terms | all levels equal | $n^d\log_b n$ | $a=b^d$: $O(n^d\log n)$ |
| $r>1$ ($a>b^d$) | grows; the last term is the biggest | the leaves (bottom level) | $n^d r^{\log_b n}=n^{\log_b a}$ | $a>b^d$: $O(n^{\log_b a})$ |
Check the last row. $r^{\log_b n}=\dfrac{a^{\log_b n}}{(b^d)^{\log_b n}}=\dfrac{a^{\log_b n}}{n^d}$ (because $b^{\log_b n}=n$). So $n^d r^{\log_b n}=a^{\log_b n}=n^{\log_b a}$. This is also the number of leaves: $a^{\log_b n}$ calls at the bottom.
Picture to remember. Root heavy = an upside-down pyramid (big top). Balanced = a rectangle. Leaf heavy = a normal pyramid (big base). Ask yourself: does the cost per level go down, stay the same or go up as you descend?
Worked example: Level table for $T(n)=3T(n/3)+n$
Problem.
Find the cost of each level for $n=27$ and the total.
Idea.
$a=b=3$, $d=1$.
- Level 0: 1 call of size 27 costs 27.
- Level 1: 3 calls of size 9: $3\cdot9=27$.
- Level 2: 9 calls of size 3: 27. Level 3: 27 calls of size 1: 27.
- Four levels ($\log_3 27+1$) each costing 27: total 108 = $n\log_3 n+n$, which is $O(n\log n)$.
Answer.
$O(n\log n)$
Common mistake.
Forgetting the last level (the leaves).
Worked example: Compare two similar recurrences
Problem.
$T_1=2T(n/2)+n^2$ and $T_2=4T(n/2)+n$. Which is bigger for large $n$?
Idea.
Compute each by the tree.
- $T_1$: $a=2<b^d=4$, root heavy: $O(n^2)$.
- $T_2$: $a=4>b^d=2$, leaves: $O(n^2)$.
- Both are $O(n^2)$ but for opposite reasons. Exam answers are equal; the working differs.
Answer.
both $O(n^2)$
Common mistake.
Assuming the larger $a$ always gives the larger answer.
Worked example: When the leaves win
Problem.
$T(n)=3T(n/2)+n$ with $T(1)=1$. Find $T(8)$ and say which level dominates.
Idea.
Compute from the bottom up.
- $T(2)=3\cdot1+2=5$.
- $T(4)=3\cdot5+4=19$.
- $T(8)=3\cdot19+8=65$.
- Level work grows by the factor $3/2$ going down, so the bottom dominates.
Answer.
$T(8)=65$; the leaves dominate.
Common mistake.
Answering $n\log n$ because the extra work is $n$.
Cost per level, then sum the levels.
| Step | Method for any exam question |
|---|---|
| 1 | Draw the first two or three levels. |
| 2 | Count the nodes and the cost on each level. |
| 3 | Find the number of levels. |
| 4 | Add the level costs. |
4. The master theorem: solve recurrences in seconds
Compare $a$ with $b^d$. Bigger: leaves win. Equal: multiply by $\log n$. Smaller: top wins.
A one-line rule for $T(n)=aT(n/b)+O(n^d)$, plus the separate rule for $T(n-1)$ types.
The question this lesson answers. Can the answer be read off without drawing the tree?
| New word | Meaning |
|---|---|
| leaf work | $n^{\log_b a}$, the cost carried by the base cases |
| root work | $f(n)$, the cost of the first call outside recursion |
| dominates | grows faster by at least a power of $n$ |
A race between two crowds: the number of small jobs at the bottom, and the work at the top. The bigger side decides the total, and a tie costs one extra factor of $\log n$.
For $T(n)=a\,T(n/b)+O(n^d)$ with $a\ge1,\ b>1,\ d\ge0$, compare $a$ with $b^d$: (1) $a<b^d\ \Rightarrow\ O(n^d)$ (2) $a=b^d\ \Rightarrow\ O(n^d\log n)$ (3) $a>b^d\ \Rightarrow\ O(n^{\log_b a})$.
Why it works: in the recursion tree, level costs are $n^d,\ (a/b^d)n^d,\ (a/b^d)^2n^d,\dots$ This is a geometric series with ratio $a/b^d$. Ratio below 1: the top wins. Ratio equal to 1: all levels equal. Ratio above 1: the bottom wins, and the number of leaves is $a^{\log_b n}=n^{\log_b a}$.
You do not need to compute $\log_b a$ unless case (3) applies. Compare $a$ and $b^d$ first. Example: $T(n)=2T(n/8)+n$: $a=2$, $b^d=8$. $2<8$, so $O(n)$.
Here are twelve recurrences solved by the rule, covering all three cases.
| Recurrence | $a$ | $b$ | $d$ | $b^d$ | Compare | Result |
|---|---|---|---|---|---|---|
| $T(n/3)+O(1)$ | 1 | 3 | 0 | 1 | $a=b^d$ | $O(\log n)$ |
| $2T(n/3)+O(n)$ | 2 | 3 | 1 | 3 | $a<b^d$ | $O(n)$ |
| $T(n/2)+O(n)$ | 1 | 2 | 1 | 2 | $a<b^d$ | $O(n)$ |
| $5T(n/5)+O(n)$ | 5 | 5 | 1 | 5 | $a=b^d$ | $O(n\log n)$ |
| $7T(n/7)+O(n)$ | 7 | 7 | 1 | 7 | $a=b^d$ | $O(n\log n)$ |
| $3T(n/2)+O(n)$ | 3 | 2 | 1 | 2 | $a>b^d$ | $O(n^{\log_2 3})\approx O(n^{1.58})$ |
| $3T(n/9)+O(n)$ | 3 | 9 | 1 | 9 | $a<b^d$ | $O(n)$ |
| $16T(n/4)+O(n)$ | 16 | 4 | 1 | 4 | $a>b^d$ | $O(n^{\log_4 16})=O(n^2)$ |
| $3T(n/4)+O(n^2)$ | 3 | 4 | 2 | 16 | $a<b^d$ | $O(n^2)$ |
| $5T(n/4)+O(n^2)$ | 5 | 4 | 2 | 16 | $a<b^d$ | $O(n^2)$ |
| $4T(n/2)+O(n^2)$ | 4 | 2 | 2 | 4 | $a=b^d$ | $O(n^2\log n)$ |
| $7T(n/2)+O(n^2)$ | 7 | 2 | 2 | 4 | $a>b^d$ | $O(n^{\log_2 7})\approx O(n^{2.81})$ |
Subtract type is not master type. $T(n)=T(n-1)+O(1)$ gives $O(n)$ and $T(n)=T(n-1)+O(n)$ gives $O(n^2)$. The size drops by one, not by a factor, so use the level-sum idea: $1+1+\dots$ (n times) or $n+(n-1)+\dots+1$.
The master theorem is for one size ratio. For $T(n)=T(n/5)+T(7n/10)+O(n)$ (Median of Medians) the sizes add to $0.2n+0.7n=0.9n<n$. When the sizes add to less than $n$, the top level dominates and $T(n)=O(n)$.
Worked example: One-line solve
Problem.
Solve $T(n)=2T(n/2)+O(n)$.
Idea.
Compare $a$ with $b^d$.
- $a=2,\ b=2,\ d=1$, so $b^d=2$.
- $a=b^d$: levels are equal.
- Multiply $n^d$ by $\log n$: $n\log n$.
Answer.
$O(n\log n)$
Worked example: Two recurrences in one question
Problem.
$T_1=5T_1(n/5)+O(n)$ and $T_2=9T_2(n/2)+O(n^2)$.
Idea.
Compare $a$ with $b^d$ separately for each.
- $T_1$: $a=5$, $b=5$, $d=1$, $b^d=5$. Equal: $O(n\log n)$.
- $T_2$: $a=9$, $b=2$, $d=2$, $b^d=4$. $9>4$: $O(n^{\log_2 9})\approx O(n^{3.17})$.
Answer.
$T_1=O(n\log n)$ and $T_2=O(n^{\log_2 9})$
Worked example: Same answer, different reasons
Problem.
$T_1=4T_1(n/4)+O(n^2)$ and $T_2=16T_2(n/4)+O(n)$.
Idea.
Compare a with b to the power d each time.
- $T_1$: $a=4$, $b^d=4^2=16$. $4<16$, the top wins: $O(n^2)$.
- $T_2$: $a=16$, $b^d=4$. $16>4$, the leaves win: $O(n^{\log_4 16})=O(n^2)$.
Answer.
Both are $O(n^2)$.
Common mistake.
Using $n\log n$ because $a=b$ in $T_1$. Equality means $a=b^d$.
| Case | Compare | Result | Cost per level | Picture | Typical example |
|---|---|---|---|---|---|
| root heavy | $a<b^d$ | $n^d$ | shrinks by factor $r<1$ | upside-down pyramid | $2T(n/2)+n^2$, $2T(n/4)+n$ |
| balanced | $a=b^d$ | $n^d\log n$ | constant | rectangle | $2T(n/2)+n$, $3T(n/3)+n$, $6T(n/6)+n$ |
| leaf heavy | $a>b^d$ | $n^{\log_b a}$ | grows by factor $r>1$ | pyramid | $4T(n/2)+n$, $5T(n/2)+n$, $9T(n/3)+n$ |
Quick decision table. Compute $b^d$ first, then compare it with $a$:
$a<b^d\Rightarrow n^d$ | $a=b^d\Rightarrow n^d\log n$ | $a>b^d\Rightarrow n^{\log_b a}$
Mnemonic: "The bigger one wins; a tie costs a log." If $b^d$ is bigger the root (the $d$) wins; if $a$ is bigger the leaves win; if they tie, every level pays.
Variations that appear in exams. The recurrences below are extra practice, solved by the same rule; the answers are computed.
| Recurrence | $a$, $b$, $d$ | $b^d$ vs $a$ | Answer |
|---|---|---|---|
| $2T(n/2)+n^2$ | 2, 2, 2 | 4 > 2 | $O(n^2)$ |
| $T(n/2)+n$ | 1, 2, 1 | 2 > 1 | $O(n)$ |
| $2T(n/2)+1$ | 2, 2, 0 | 1 < 2 | $O(n)$ |
| $8T(n/2)+n^2$ | 8, 2, 2 | 4 < 8 | $O(n^3)$ |
| $3T(n/2)+n$ | 3, 2, 1 | 2 < 3 | $O(n^{\log_2 3})\approx O(n^{1.58})$ |
| $4T(n/4)+n$ | 4, 4, 1 | 4 = 4 | $O(n\log n)$ |
| $9T(n/3)+n^2$ | 9, 3, 2 | 9 = 9 | $O(n^2\log n)$ |
| $T(n/4)+1$ | 1, 4, 0 | 1 = 1 | $O(\log n)$ |
Recurrences that are not of master form. (1) Subtract type $T(n)=T(n-1)+n^k$: add the levels. $n^k+(n-1)^k+\dots+1\approx\dfrac{n^{k+1}}{k+1}$, so the answer is $O(n^{k+1})$. (2) Unequal split $T(n)=T(n/3)+T(2n/3)+n$: the sizes add up to $n$, so each level costs $n$, and the tallest branch has $\log_{3/2}n$ levels: $O(n\log n)$. (3) Splits adding to less than $n$: $T(n/5)+T(7n/10)+n$ (sizes add to $0.9n$) gives $O(n)$. (4) $T(n)=2T(n-1)+1$ doubles each step: $O(2^n)$.
| Recurrence | Method | Answer |
|---|---|---|
| $T(n-1)+1$ | sum $1+1+\dots+1$ | $O(n)$ |
| $T(n-1)+n$ | sum $n+(n-1)+\dots+1=n(n+1)/2$ | $O(n^2)$ |
| $T(n-1)+n^2$ | sum of squares $\approx n^3/3$ | $O(n^3)$ |
| $T(n-1)+\log n$ | sum of logs $=\log n!\approx n\log n$ | $O(n\log n)$ |
| $2T(n-1)+1$ | 1, 3, 7, 15, … $=2^n-1$ | $O(2^n)$ |
| $T(n/3)+T(2n/3)+n$ | levels cost $n$ each, $\log_{3/2}n$ levels | $O(n\log n)$ |
| Common mistake | Typical wrong answer | Fix |
|---|---|---|
| Using $b$ instead of $b^d$ | $3T(n/3)+n^2$ called $n\log n$ | $b^d=9$, $a=3<9$ so $O(n^2)$ |
| Forgetting the base of the exponent | $9T(n/3)+n$ called $O(n)$ | $b^d=3<a=9$: leaves, $O(n^2)$ |
| Treating subtract type as halving | $T(n-1)+n$ called $n\log n$ | sum the levels: $O(n^2)$ |
| Reading the $O(n)$ as $d=0$ | — | $f(n)=n^d$: for $n$, $d=1$; for constant, $d=0$ |
Worked example: Unfamiliar form
Problem.
$T(n)=T(n/4)+T(3n/4)+n$. Complexity?
Idea.
Not master form. Look at the sizes: $\frac14+\frac34=1$.
- Every level splits the same total size $n$ among its calls, so each level costs $n$.
- The tallest branch follows the $3/4$ side: $\log_{4/3}n$ levels.
- Total about $n\log n$.
Answer.
$O(n\log n)$
Common mistake.
Trying to read $a$ and $b$ from two different fractions.
Worked example: A square root as extra work
Problem.
Solve $T(n)=2T(n/4)+O(\sqrt n)$.
Idea.
Write the root as a power: $d=\tfrac12$.
- $a=2$, $b=4$, $d=\tfrac12$.
- $b^d=\sqrt4=2$.
- $a=b^d$, so all levels cost the same.
Answer.
$O(\sqrt n\,\log n)$
Common mistake.
Taking $d=1$ because a root looks like ordinary work.
Leaves win, tie adds a log, or the top wins.
| Step | Method for any exam question |
|---|---|
| 1 | Read a, b and d. |
| 2 | Compare a with b to the power d. |
| 3 | Pick the matching case. |
5. Counting inversions
An inversion is a bigger number standing before a smaller one. Count them per element.
What an inversion is, how to count them fast by hand, the maximum possible, and the merge-sort method.
The question this lesson answers. How can you count out-of-order pairs faster than checking every pair?
| New word | Meaning |
|---|---|
| inversion | a pair $i<j$ with $L[i]>L[j]$ |
| merge step | joining two sorted halves into one sorted list |
| cross inversion | an inversion with one element in each half |
In a list $L$, positions $i<j$ form an inversion if $L[i]>L[j]$. So a bigger number comes before a smaller one. A sorted list has 0 inversions. A reverse-sorted list of $n$ numbers has the maximum, $\binom n2=\frac{n(n-1)}{2}$.
Why it works. While merging two sorted halves, taking an item from the right half means it is smaller than everything still waiting on the left, so those pairs are counted all at once.
Think of a queue where everyone should be in order of height, shortest first. Each time a tall person stands in front of a shorter person, that is one inversion. The count measures how far the line is from being in order.
Hand method (use this in the exam). Go through the list left to right. For each element, count how many smaller elements are still to its right. Add all the counts. Watch it on $L=[5,2,4,1,3]$.
Counting inversions, element by element
5 has these smaller values (red) to its right: 2, 4, 1, 3. That adds 4.
2 has these smaller values (red) to its right: 1. That adds 1.
4 has these smaller values (red) to its right: 1, 3. That adds 2.
1 has no smaller values to its right. That adds 0.
3 has no smaller values to its right. That adds 0.
The same count as a table
| $L[i]$ | smaller elements to its right | count |
|---|---|---|
| 5 | 2, 4, 1, 3 | 4 |
| 2 | 1 | 1 |
| 4 | 1, 3 | 2 |
| 1 | none | 0 |
| 3 | none | 0 |
Maximum inversions for $n$ distinct elements: $\binom n2=\dfrac{n(n-1)}2$ (reverse-sorted list). Minimum length for $k$ inversions: the smallest $n$ with $\dfrac{n(n-1)}2\ge k$.
Worked example: Minimum length for 10 inversions
Problem.
What is the smallest length of a list that can have exactly 10 inversions?
Idea.
Use $n(n-1)/2\ge10$.
- Try $n=4$: $4\cdot3/2=6<10$. Not enough.
- Try $n=5$: $5\cdot4/2=10\ge10$. Works.
- A reverse-sorted list of 5 has exactly 10.
Answer.
$n=5$
Common mistake.
Using $n=10$ because "10 inversions". The count of pairs grows faster than $n$.
The fast method: merge sort counting. Counting by hand is $O(n^2)$. Merge sort counts inversions in $O(n\log n)$. Split the list in half, count inversions inside each half, then count the cross inversions while merging. Watch one merge of two sorted halves.
Counting cross inversions during a merge
Both halves are sorted. Compare the two front values and always take the smaller one.
1 from the right is smaller than every waiting left value.
1 jumps ahead of 3 left values, so add 3.
2 from the left is not larger: taking it creates no inversion.
2 moves to the output. The count stays 3.
3 from the right is smaller than every waiting left value.
3 jumps ahead of 2 left values, so add 2.
One half is used up, so copy 4, 5. Cross inversions: 5.
During a merge, when an element from the right half is taken before elements still waiting in the left half, it forms an inversion with every waiting left element. That is why we add len(left) - i.
Full merge-sort count for [5, 2, 4, 1, 3]
| sub-list | left sorted | right sorted | cross inversions | merged |
|---|---|---|---|---|
| [5, 2] | [5] | [2] | 1 | [2, 5] |
| [1, 3] | [1] | [3] | 0 | [1, 3] |
| [4, 1, 3] | [4] | [1, 3] | 2 | [1, 3, 4] |
| [5, 2, 4, 1, 3] | [2, 5] | [1, 3, 4] | 4 | [1, 2, 3, 4, 5] |
Merge sort that counts inversions
Merge sort splits until pieces have one item, then merges. Inversions are counted during the merges.
Split into
[5, 2]and[4, 1, 3], and sort each half first.Split into
[5]and[2], and sort each half first.Merging
[5]and[2]: 2 passes 1 left value, so add 1.Copy the leftovers and write
[2, 5]back. This range is sorted.Split into
[4]and[1, 3], and sort each half first.Split into
[1]and[3], and sort each half first.Merging
[1]and[3]: 1 is the smaller front value. No inversion.Copy the leftovers and write
[1, 3]back. This range is sorted.Merging
[4]and[1, 3]: 1 passes 1 left value, so add 1.Merging
[4]and[1, 3]: 3 passes 1 left value, so add 1.Copy the leftovers and write
[1, 3, 4]back. This range is sorted.Merging
[2, 5]and[1, 3, 4]: 1 passes 2 left values, so add 2.Merging
[2, 5]and[1, 3, 4]: 2 is the smaller front value. No inversion.Merging
[2, 5]and[1, 3, 4]: 3 passes 1 left value, so add 1.Merging
[2, 5]and[1, 3, 4]: 4 passes 1 left value, so add 1.Copy the leftovers and write
[1, 2, 3, 4, 5]back. This range is sorted.Sorted
[1, 2, 3, 4, 5]with 7 inversions, in $O(n\log n)$.
Merge-sort counting: $T(n)=2T(n/2)+O(n)=O(n\log n)$. Brute force: $O(n^2)$.
Worked example: A stricter kind of inversion
Problem.
Count pairs $i<j$ with $L[i]>2\,L[j]$ in $L=[10, 2, 15, 4, 1, 6]$.
Idea.
The same hand method with a stricter test: compare with twice the later value.
- For 10: later values with twice below 10 are 2, 4, 1: 3.
- For 2: no later value qualifies: 0.
- For 15: later values with twice below 15 are 4, 1, 6: 3.
- For 4: later values with twice below 4 are 1: 1.
- For 1: no later value qualifies: 0.
Answer.
7
Common mistake.
Counting ordinary inversions, or counting a pair where the value is exactly double.
Do not count a pair twice, do not count pairs with $i>j$, and equal numbers are not inversions because $L[i]>L[j]$ must be strict.
| Idea | Condition | Counts equal values? | Max for $n$ | Example on $[3,1,2]$ |
|---|---|---|---|---|
| inversion | $i<j$ and $L[i]>L[j]$ | no | $n(n-1)/2$ | 2 pairs: (3,1), (3,2) |
| significant inversion | $i<j$ and $L[i]>2L[j]$ | no | less than $n(n-1)/2$ | 1 pair: (3,1) |
| sorted order pair | $i<j$ and $L[i]<L[j]$ | — | — | (1,2) |
| equal pair | $L[i]=L[j]$ | never an inversion | — | none |
Why the maximum is $n(n-1)/2$. There are $\binom n2$ pairs of positions $i<j$. A pair is an inversion or it is not, so the count cannot exceed the number of pairs. The reversed list makes every pair an inversion. Average. In a random arrangement of distinct numbers each pair is in the wrong order with probability $\tfrac12$ (by symmetry), so the average count is $\dfrac12\binom n2=\dfrac{n(n-1)}{4}$.
Link to bubble sort (). One swap of two adjacent elements that are out of order removes exactly one inversion. So the number of swaps bubble sort makes equals the number of inversions. Sorted list: 0 swaps. Reversed list: $n(n-1)/2$ swaps.
Mnemonic "STR": Smaller To the Right. For every element, count the smaller ones on its right. Add. Never look left.
| List | Inversions | Reason |
|---|---|---|
| $[1,2,3,4]$ | 0 | already sorted |
| $[2,1,4,3]$ | 2 | two adjacent swaps needed |
| $[4,3,2,1]$ | 6 | reversed: $4\cdot3/2$ |
| $[2,2,1]$ | 2 | $(2,1)$ twice; $(2,2)$ is not an inversion |
| $[3,1,4,2]$ | 3 | (3,1), (3,2), (4,2) |
Worked example: Tricky: duplicates and a swap
Problem.
List $[2,2,1]$. (a) Number of inversions. (b) After swapping the last two elements, how does the count change?
Idea.
Equal values are not inversions.
- (a) Pairs: (2,2): equal, no. (2,1): yes. (2,1): yes. Total 2.
- (b) Swap last two: $[2,1,2]$. Pairs: (2,1) yes, (2,2) no, (1,2) no. Total 1.
- Swapping an out-of-order adjacent pair removed one inversion, as the bubble-sort link predicts.
Answer.
(a) 2, (b) 1
Common mistake.
Counting the equal pair (2,2).
Worked example: Merge-sort counting on a new list
Problem.
Count inversions of $[4,3,2,1]$ with the merge method.
Idea.
Split, count inside each half, add the cross count.
- Left $[4,3]$: 1 inversion. Right $[2,1]$: 1 inversion. After sorting: left $[3,4]$, right $[1,2]$.
- Merge: 1 is smaller than both waiting left elements (3, 4): +2. 2 is smaller than both: +2. Cross total 4.
- Total $=1+1+4=6=\binom42$.
Answer.
6
Worked example: Equal values
Problem.
Count the inversions of $[3,1,3,2]$.
Idea.
A pair counts only when the earlier value is strictly larger.
- The first 3 beats 1 and 2: two pairs.
- The two 3s are equal: no pair.
- The 1 beats nothing to its right.
- The second 3 beats 2: one pair.
Answer.
$3$
Common mistake.
Counting the pair of equal 3s.
Right item taken: add what is left on the left.
| Step | Method for any exam question |
|---|---|
| 1 | Split the list. |
| 2 | Count inside each half. |
| 3 | Count across while merging. |
| 4 | Add the three counts. |
6. Quick Select: find the $k$-th smallest without sorting
Choose a pivot, split smaller and larger around it, and look only in the side where the answer lives.
Partition around a pivot, then keep only the side that contains the answer.
The question this lesson answers. How do you find the k-th smallest value without sorting everything?
| New word | Meaning |
|---|---|
| pivot | the element used to split the list |
| partition | rearranging so smaller elements come before the pivot and larger ones after |
| rank | the position an element would have in sorted order |
Problem. Given an unsorted list, find its $k$-th smallest element ($k=1$ is the minimum, $k=n$ the maximum). Sorting everything costs $O(n\log n)$. Quick Select does better by throwing half the list away each time (on a good day).
You want the 3rd shortest student in a line. Pick one student as a marker. Ask everyone to step to the left of the marker if shorter, right if taller. Now if 4 students stand on the left, the marker is the 5th shortest. Your 3rd shortest is somewhere in the left group, so you can ignore everyone else.
Partition with pivot $p$ rearranges the list so all elements $\le p$ come first, then $p$, then all elements $>p$. After it, the pivot is at its final sorted position.
Why it works. After partitioning, the pivot is in its final place, so only one side can contain the answer and the other is ignored.
While scanning, the list is always: pivot · small zone (positions up to $i$, all ≤ pivot) · large zone (after $i$ up to $j$, all > pivot) · unseen. A new small element is swapped with the first large one (position $i+1$), which keeps both zones unbroken. A new large element needs no move.
Partition [5, 9, 2, 8, 4, 7, 1] with pivot 5
Pivot = first value 5.
imarks the end of the zone of values ≤ pivot (empty now);jwill scan the rest.j=1: 9 is bigger than the pivot. Leave it; onlyjmoves on.j=2: 2 belongs in the small zone. Grow it (i=1) and swap positions 1 and 2.2 is now inside the small zone; the bigger value 9 moved right.
j=3: 8 is bigger than the pivot. Leave it; onlyjmoves on.j=4: 4 belongs in the small zone. Grow it (i=2) and swap positions 2 and 4.4 is now inside the small zone; the bigger value 9 moved right.
j=5: 7 is bigger than the pivot. Leave it; onlyjmoves on.j=6: 1 belongs in the small zone. Grow it (i=3) and swap positions 3 and 6.1 is now inside the small zone; the bigger value 8 moved right.
The scan is over. Swap the pivot into position
i=3, the end of the small zone.5 is at index 3, its final sorted place: smaller or equal on the left, larger on the right.
partition (first element as pivot): exactly what the 2022 passage describes
def partition(L, lower, upper):
pivot = L[lower]
i = lower
for j in range(lower + 1, upper + 1):
if L[j] <= pivot:
i += 1
L[i], L[j] = L[j], L[i]
L[lower], L[i] = L[i], L[lower]
return i
Now the main function from the Jul 2022 comprehension PYQ.
mystery = Quick Select
def mystery(L, lower, upper, k):
if (k > 0 and k <= upper - lower + 1):
pos = partition(L, lower, upper)
if (pos - lower == k - 1):
return L[pos]
if (pos - lower > k - 1):
return mystery(L, lower, pos - 1, k)
else:
return mystery(L, pos + 1, upper, k - pos + lower - 1)
The pivot's rank inside the current range is $\texttt{pos} - \texttt{lower} + 1$. Going left, the smallest items are still there, so $k$ stays. Going right, you throw away exactly that many smaller items, so the new $k$ is $k - (\texttt{pos}-\texttt{lower}+1)$.
Run on [5, 9, 2, 8, 4, 7, 1], k = 6
| step | range after partition | pivot | pivot rank | k | decision |
|---|---|---|---|---|---|
| 1 | [1, 2, 4, 5, 9, 7, 8] | 5 | 4 | 6 | rank < k: go right, new k = 6 − 4 = 2 |
| 2 | [8, 7, 9] | 9 | 3 | 2 | rank > k: go left, same k |
| 3 | [7, 8] | 8 | 2 | 2 | rank = k: return 8 |
Best / average case: the pivot splits the list roughly in half, so $T(n)=T(n/2)+O(n)$, which is $n+n/2+n/4+\dots=2n=O(n)$. Worst case: the pivot is always the smallest or largest, so $T(n)=T(n-1)+O(n)=n+(n-1)+\dots+1=O(n^2)$.
Measured worst case
| $n$ | comparisons (sorted input, last element wanted) | $n(n-1)/2$ |
|---|---|---|
| 4 | 6 | 6 |
| 8 | 28 | 28 |
| 16 | 120 | 120 |
| 32 | 496 | 496 |
$k$-th largest of $n$ elements is the $(n-k+1)$-th smallest. Questions in the PYQs ask "kth largest"; the algorithm is the same.
Worked example: Which case is Quick Select linear?
Problem.
State when Quick Select is $O(n)$ and when it is $O(n^2)$.
- Linear on average, because a random pivot splits the list into reasonable parts most of the time.
- $O(n^2)$ in the worst case, if the pivot is always the minimum or maximum (for example a sorted list with the first element as pivot).
- To guarantee $O(n)$ in the worst case use Median of Medians for the pivot (next section).
Answer.
Average $O(n)$, worst $O(n^2)$.
| Method | Pivot rule | Best / average | Worst | Extra space | Note |
|---|---|---|---|---|---|
| Sort, then index | — | $O(n\log n)$ | $O(n\log n)$ | $O(1)$ or $O(n)$ | does more work than needed |
| Quick Select, first-element pivot | first element | $O(n)$ | $O(n^2)$ (sorted input) | $O(1)$ (loop) / stack | PYQ mystery |
| Quick Select, random pivot (A.) | random element | $O(n)$ expected | $O(n^2)$ (unlikely) | — | improves the expected time, not the worst case |
| Fast Select: Quick Select + Median of Medians | MoM | $O(n)$ | $O(n)$ | $O(n)$ | guaranteed linear; big constant |
| Max-heap of size $k$ (A.) | — | $O(n\log k)$ | $O(n\log k)$ | $O(k)$ | scans all $n$ items |
Why average $O(n)$? If each partition cuts the list roughly in half the total work is $n+\frac n2+\frac n4+\dots<2n$ (a geometric series). Why worst $O(n^2)$? If each pivot is the minimum or maximum the sizes are $n, n-1, n-2,\dots$ and the total is $n+(n-1)+\dots+1=n(n+1)/2$.
| Question says | Ask the algorithm for | Reason |
|---|---|---|
| $k$-th smallest | rank $k$ | as is |
| $k$-th largest of $n$ | rank $n-k+1$ (smallest) | largest is the $n$-th smallest |
| median of $n$ (odd) | rank $(n+1)/2$ | middle |
| minimum | rank 1 | — |
| maximum | rank $n$ | — |
Worked example: Trace for the 2nd largest
Problem.
Find the 2nd largest of $[9,4,7,1,8,3,6]$ by Quick Select.
Idea.
2nd largest of 7 elements = rank $7-2+1=6$.
- Partition around 9: pivot ends at position 6 (rank 7). Rank 7 > 6: search the left part $[6,4,7,1,8,3]$ with the same $k=6$.
- Partition around 6: left part is $[3,4,1]$ and the pivot sits at rank 4. $4<6$: search the right part with $k=6-4=2$.
- Right part is $[8,7]$ with $k=2$. Partition it around 8: 7 goes left, so the pivot 8 has rank $r=2$. Since $r=k$, return 8.
- So the 2nd largest is 8.
Answer.
8
Common mistake.
Asking for rank 2 instead of rank 6.
Recognition cues. "pos - lower" and "k - pos + lower - 1" in code = Quick Select. "worst case becomes $O(n)$" = Median of Medians. "expected linear" = random pivot.
Worked example: Sorted input, first element as pivot
Problem.
Quick Select with the first element as pivot runs on $[1,2,3,4,5,6]$. How many comparisons does it make for $k=6$, and for $k=1$?
Idea.
Count one comparison for each other element in the current range.
- For $k=6$ the ranges have sizes $6,5,4,3,2,1$.
- The comparisons are $5+4+3+2+1+0=15$.
- For $k=1$ the first pivot is already the answer, after 5 comparisons.
Answer.
$15$ and $5$.
Common mistake.
Saying sorted input is always the worst case, whatever $k$ is.
Partition, then go one way.
| Step | Method for any exam question |
|---|---|
| 1 | Pick a pivot and partition. |
| 2 | Compare the pivot's position with k. |
| 3 | Continue on one side only, adjusting k. |
7. Median of Medians: a pivot you can trust
Cut into blocks of 5, take each block's median, then take the median of those medians. That pivot is never near the ends.
How Median of Medians (MoM) picks a good pivot, how to dry-run the code, and why it makes Quick Select $O(n)$ in the worst case.
The question this lesson answers. How can a pivot be guaranteed never to be very bad?
| New word | Meaning |
|---|---|
| block | a group of 5 neighbouring elements |
| block median | the middle value of a sorted block |
| good pivot | one that is guaranteed to discard a fixed fraction of the list |
Choosing a typical height in a large school: take the middle pupil of every small group, then the middle of those. The result cannot be extreme.
A random pivot can be unlucky. Median of Medians builds a pivot that is guaranteed to be in the middle part of the sorted order, so the bad worst case disappears.
Choosing a pivot (this is what Median of Medians does) and selecting the k-th smallest (Quick Select, which partitions around that pivot) are separate steps with separate costs. Read each question for which one it asks about.
MoM pivot. (1) Cut the list into blocks of 5 (the last block may be shorter). (2) Sort each block and take its middle element. (3) Collect those medians into a new list. (4) Repeat on that list until at most 5 remain, then sort it and take the middle. The final value is the pivot.
Why it works. The median of the block medians has a fixed fraction of the items on each side, so every round discards a fixed share.
MoM from the Aug 2025 PYQ, with indexes safe for short blocks
def MoM(L):
if len(L) <= 5:
L.sort()
return L[len(L)//2]
M = []
for i in range(0, len(L), 5):
X = L[i:i+5]
X.sort()
M.append(X[len(X)//2])
return MoM(M)
Dry run of MoM on a 12-item list
Round 1, block 1: sort the block and keep its middle value 14.
Round 1, block 2: sort the block and keep its middle value 11.
Round 1, block 3: sort the block and keep its middle value 16.
Round 2: only 3 items are left, so sort them and take the middle: MoM returns 14.
Read the index rule in the code. The Aug 2025 question's code uses index 2; the code above and the Apr 2026 code use len(X)//2. For blocks of 5 they agree. For a short last block they can differ: a block of 4 gives 4//2 = 2 (same), but a block of 2 has no index 2, while 2//2 = 1 works.
Why is it a good pivot? Look at the picture. Sort each block of 5 (columns, smallest at the top). Order the columns by their medians. The pivot is the middle column's median (yellow).
| Fact | Count for $n=25$ (5 blocks of 5) |
|---|---|
| elements in blocks whose median $\ge$ pivot (3 blocks) | at least $3\cdot3=9$ |
| elements $\ge$ pivot guaranteed | $9\ge0.3\cdot25=7.5$ |
| larger side at most | $25-9=16\le0.7\cdot25=17.5$ |
The 30/70 count above uses the pivot that is the exact median of the block medians (full Fast Select gets it by calling selection again on that list). Then each side has at most about $\dfrac{7n}{10}$ elements. The short code above only approximates that median by repeating the block step.
Cost, one job at a time. Choosing the pivot with the short code: $P(n)=P(n/5)+O(n)=O(n)$. Selecting with an exact median of medians: $T(n)\le T(n/5)+T(7n/10)+cn$, where the first term finds that median and the second continues on the larger side. The two sizes add to $0.9n$, so the levels cost at most $cn,\ 0.9cn,\ 0.81cn,\dots$, which adds to at most $10cn$: $T(n)=O(n)$. Some questions simplify this to $T(n)=T(n/2)+O(n)=O(n)$.
Why blocks of 5? Take blocks of size $b$ (odd). Half of the blocks have a median at least the pivot, and in each such block $\frac{b+1}{2}$ elements are at least the pivot. So at least about $\frac{b+1}{4b}n$ elements are $\ge$ pivot, and the same for $\le$ pivot. The larger side has at most $\left(1-\frac{b+1}{4b}\right)n$ elements. Finding the median of the $n/b$ block medians costs $T(n/b)$. Total: $T(n)\le T(n/b)+T\!\left(\left(1-\frac{b+1}{4b}\right)n\right)+O(n)$.
| block size $b$ | larger side at most (fraction of $n$) | $\frac1b+$ larger side | Result |
|---|---|---|---|
| 3 | 0.6667 | 1.0000 | $O(n\log n)$ |
| 5 | 0.7000 | 0.9000 | $O(n)$ |
| 7 | 0.7143 | 0.8571 | $O(n)$ |
| 9 | 0.7222 | 0.8333 | $O(n)$ |
If the two fractions add to 1 or more, the work per level does not shrink and we get $O(n\log n)$. With $b=3$ the fractions are $\frac13+\frac23=1$: no good. With $b=5$: $\frac15+\frac7{10}=0.9<1$: the total work shrinks every level and $T(n)=O(n)$. That is why the algorithm uses 5. (Block sizes 7 and 9 also work; the textbook uses 5.)
Mnemonic "5-Mid-Mid": chop into 5s, take the mid of each, take the mid of the mids. The result is a pivot that is never in the bottom 30 percent or top 30 percent.
Worked example: MoM on a 15-element list
Problem.
MoM with index len(X)//2 on $[9,1,8,2,7,3,6,4,5,15,14,13,12,11,10]$.
Idea.
3 blocks of 5.
- Block 1: $[9,1,8,2,7]$ sorted $[1,2,7,8,9]$, median 7.
- Block 2: $[3,6,4,5,15]$ sorted $[3,4,5,6,15]$, median 5.
- Block 3: $[14,13,12,11,10]$ sorted $[10,11,12,13,14]$, median 12.
- Medians $[7,5,12]$ (3 items, at most 5): sorted $[5,7,12]$, index $3//2=1$ gives 7.
Answer.
7
Common mistake.
Returning the true median 8 of the whole list. MoM returns a good pivot, not necessarily the exact median.
Worked example: A short list and a fixed index
Problem.
The version of MoM that returns L[2] is called on $[9,1,5]$. What is returned? What if the list has only two items?
Idea.
The list is sorted and index 2 is read, whatever the length.
- Sorted: $[1,5,9]$.
- Index 2 is the third item, 9, which is the largest.
- With two items there is no index 2.
Answer.
Returns 9; with two items it raises IndexError.
Common mistake.
Assuming L[2] always means the median.
Which pivot rules give a worst case of $O(n)$?
A worst-case promise needs two things on every round: the larger side is at most a fixed fraction of $n$, and finding the pivot costs no more than $O(n)$.
| Pivot rule | Worst case | Why |
|---|---|---|
| One random element | $O(n^2)$ | Bad luck can pick the smallest every time. Only the expected time is $O(n)$. |
| Median of a random sample of $k$ elements, $k$ fixed | $O(n^2)$ | The sample can be the $k$ smallest. Its median then removes only a few elements, a constant number: $T(n)=T(n-c)+O(n)$. |
| Sort the current part and take its true median | $O(n\log n)$ | The split is perfect but the sort is too dear: $T(n)=T(n/2)+O(n\log n)=O(n\log n)$. |
| Median of Medians | $O(n)$ | Always a constant-fraction split, found in linear time. |
A bigger fixed sample makes a bad pivot less likely. It does not make it impossible, and worst case asks about what is possible.
| Statement about MoM | True or false | Reason |
|---|---|---|
| It returns the exact median | false | it returns the median of block medians |
| It runs in $O(n)$ time | true (for the pivot) | recurrence $T(n/5)+O(n)$ |
| It guarantees a pivot between the 30th and 70th percentile | true | counting argument above |
| It makes plain Quick Select $O(n)$ in the worst case | true (Fast Select) | balanced split guaranteed |
| It is used by random-pivot Quick Select | false | that picks a random element |
Exam facts. Finding the median with MoM: $O(n)$. Quick Select with MoM pivot (Fast Select): $O(n)$ in the worst case. Plain Quick Select: $O(n)$ average, $O(n^2)$ worst.
Blocks of five buy a guaranteed split.
| Step | Method for any exam question |
|---|---|
| 1 | Make blocks of five. |
| 2 | Take each block's median. |
| 3 | Select the median of those medians. |
| 4 | Partition around it. |
8. Closest pair of points
Split by a vertical line, solve both sides, then only check points near the line.
Finding the two closest points among $n$ points, using divide and conquer.
The question this lesson answers. How do you find the closest two points without comparing all pairs?
| New word | Meaning |
|---|---|
| dividing line | the vertical line that splits the points into halves |
| $d$ | the smaller of the two distances found in the halves |
| strip | the points within $d$ of the dividing line |
Finding the two closest houses in a town cut by a road: search each side, then walk only the narrow strip beside the road.
Problem. Given $n$ points in the plane, find the two with the smallest distance between them. The distance used is the Euclidean distance $\sqrt{(x_1-x_2)^2+(y_1-y_2)^2}$.
Brute force checks every pair: $\binom n2$ pairs, $O(n^2)$ time. Divide and conquer does it in $O(n\log n)$.
Why it works. Only pairs closer than the best found on either side can matter, and they must lie in a narrow strip where each point has few neighbours to check.
Closest pair: divide, then check the δ-strip
8 points. Brute force would check all 28 pairs.
Sort by x and cut at x = 5: 4 points on each side.
The closest pair on the left is (1, 3) and (3, 1), distance 2.828.
On the right it is (7, 6) and (8, 4), distance 2.236.
δ = min of the two = 2.236. A closer crossing pair must have both points within δ of the line.
(3, 1) to (6, 2) = 3.162, not better than 2.236.
From (3, 1), the next point (4, 5) is 4 higher, at least the best 2.236. It and all later points are skipped.
From (6, 2), the next point (4, 5) is 3 higher, at least the best 2.236. It and all later points are skipped.
(4, 5) to (7, 6) = 3.162, not better than 2.236.
The answer is (7, 6) and (8, 4), distance 2.236. It lies inside one half, but the strip still had to be checked.
Algorithm: (1) sort points by $x$; (2) split into two halves; (3) recursively find $\delta_L$, $\delta_R$ and set $\delta=\min(\delta_L,\delta_R)$; (4) combine: check pairs that cross the line, using only points within $\delta$ of it, sorted by $y$; each point needs to be compared with only a constant number (at most 7) of the next points. $T(n)=2T(n/2)+O(n)=O(n\log n)$.
Why does the combine step cost only $O(n)$? Inside the strip, any two points closer than $\delta$ must be within a small window in $y$, and at most a constant number of points can be packed there without two of them being closer than $\delta$ on the same side. So each point checks a constant number of neighbours.
The combine step is not a comparison of every left point with every right point. That would cost $O(n^2)$ and destroy the speed-up.
Base case. When at most 3 points remain, use brute force: at most 3 pair checks. Splitting 3 points would leave a half with a single point and no pair, so the recursion overhead is larger than the saving.
Worked example: Recurrence of closest pair
Problem.
State the recurrence and solve it.
Idea.
Two half-size calls plus a linear combine step.
- $a=2$, $b=2$, combine $=O(n)$ so $d=1$.
- $b^d=2=a$: the equal case.
- $T(n)=O(n\log n)$.
Answer.
$O(n\log n)$
Common mistake.
Forgetting the initial sort by $x$ (cost $O(n\log n)$ once, not inside the recursion).
| Method | Steps | Time | Needs |
|---|---|---|---|
| Brute force | check all $\binom n2$ pairs | $O(n^2)$ | nothing |
| Divide and conquer | sort by $x$, split, recurse, strip check | $O(n\log n)$ | strip sorted by $y$ |
| Sort by $x$ only, compare neighbours (A.) | compare adjacent points in sorted order | wrong in general | the closest pair may not be adjacent in $x$ |
The packing argument. Take a point $p$ in the strip and look at points whose $y$ is within $\delta$ above $p$. They lie in a $2\delta\times\delta$ window. Cut the window into 8 squares of side $\delta/2$. Two points of the same half are at least $\delta$ apart, but the diagonal of a $\delta/2$ square is only $\delta/\sqrt2<\delta$, so each square holds at most one point. So at most 7 other points need to be checked per strip point: a constant, which makes the combine step $O(n)$.
Memory chain. Sort by $x$ → split → solve both halves → $\delta=\min$ → keep only the strip → sort by $y$ → compare each point with the next few → answer. Cost: $2T(n/2)+O(n)=O(n\log n)$.
| Common mistake | Correction |
|---|---|
| Comparing every left point with every right point | that is $O(n^2)$; only strip points need checking |
| Forgetting that the closest pair may cross the line | only the strip check can rule this out; here the best crossing pair (3.162) loses to 2.236 |
| Thinking brute force at 3 points is for speed in large inputs | it is the base case where recursion overhead is not worth it |
| Saying $O(n^2)$ because there are strip comparisons | each strip point does a constant number of checks |
Worked example: Distance between two points
Problem.
Distance between $(1,2)$ and $(4,6)$.
Idea.
Use $\sqrt{\Delta x^2+\Delta y^2}$.
- $\Delta x=3$, $\Delta y=4$.
- $\sqrt{9+16}=5$.
Answer.
5
Worked example: Who is in the strip?
Problem.
The dividing line is $x=5$ and $\delta=2$. Which of the x-coordinates $2.9, 3.5, 6.9, 7.2$ belong to the strip?
Idea.
Keep a point when its distance to the line is less than $\delta$.
- The distances are $2.1, 1.5, 1.9, 2.2$.
- Only $1.5$ and $1.9$ are below 2.
Answer.
$3.5$ and $6.9$
Common mistake.
Using a strip of total width $\delta$ instead of $\delta$ on each side.
Solve both sides, then search only the strip.
| Step | Method for any exam question |
|---|---|
| 1 | Sort and split by x. |
| 2 | Solve both halves. |
| 3 | Let d be the smaller answer. |
| 4 | Check the strip of width d on each side. |
9. Multiplying large numbers: Karatsuba
Cut both numbers in half. Three smaller products plus some adding and shifting rebuild the answer.
How three half-size multiplications can do the work that looks like it needs four.
The question this lesson answers. Can two n-digit numbers be multiplied with fewer than about n² digit multiplications?
Start with school multiplication. Every digit of one number meets every digit of the other, so two $n$-digit numbers need $n^2$ single-digit multiplications.
Split both numbers into a high and a low half of $m=n/2$ digits: $x=a\cdot10^m+b$ and $y=c\cdot10^m+d$. Multiplying out:
$$xy = ac\cdot10^{2m} + (ad+bc)\cdot10^{m} + bd$$
That uses four half-size products $ac, ad, bc, bd$. Shifting by a power of 10 and adding cost only $O(n)$. So $T(n)=4T(n/2)+O(n)$, which is $O(n^2)$: splitting alone gains nothing.
$p=ac,\qquad q=bd,\qquad r=(a+b)(c+d)$
$$xy = p\cdot10^{2m} + (r-p-q)\cdot10^{m} + q$$
Three multiplications of about half the size. The extra additions and subtractions cost $O(n)$.
Worked example: Worked: 4731 × 2658
Problem.
Multiply 4731 by 2658 using one split.
Idea.
m = 2, so a = 47, b = 31, c = 26, d = 58.
- $p = 47\times26 = 1222$.
- $q = 31\times58 = 1798$.
- $r = (47+31)(26+58) = 78\times84 = 6552$.
- Middle: $r-p-q = 6552-1222-1798 = 3532$.
- Assemble: $1222\cdot10^4 + 3532\cdot10^2 + 1798 = 12220000 + 353200 + 1798$.
Answer.
$12574998$
Common mistake.
Writing the middle term as r alone, or shifting it by 10^4 instead of 10^2.
One level deeper: p = 47 × 26 by the same rule (m = 1)
| step | calculation | value |
|---|---|---|
| split | a=4, b=7, c=2, d=6 | - |
| p | 4 × 2 | 8 |
| q | 7 × 6 | 42 |
| r | (4+7) × (2+6) = 11 × 8 | 88 |
| middle | 88 − 8 − 42 | 38 |
| assemble | 8·100 + 38·10 + 42 | 1222 |
Karatsuba on Python integers
def karatsuba(x, y): # x, y are non-negative integers
if x < 10 or y < 10: # base case: a one-digit factor
return x * y
m = max(len(str(x)), len(str(y))) // 2
a, b = divmod(x, 10 ** m) # x = a * 10**m + b
c, d = divmod(y, 10 ** m)
p = karatsuba(a, c)
q = karatsuba(b, d)
r = karatsuba(a + b, c + d)
return p * 10 ** (2 * m) + (r - p - q) * 10 ** m + q
Write $m$ with $\texttt{//}$. With $\texttt{/}$ it becomes a float, the powers of 10 become floats, and large products lose digits.
The recurrence. $T(n)=3T(n/2)+O(n)$. In the recursion tree, level $i$ has $3^i$ calls of size $n/2^i$, so it costs about $n\,(3/2)^i$. The costs grow going down, so the leaves decide: $3^{\log_2 n}=n^{\log_2 3}\approx n^{1.585}$.
| Digits n | School / four products: n² | Karatsuba leaves: 3^(log₂ n) |
|---|---|---|
| 4 | 16 | 9 |
| 8 | 64 | 27 |
| 16 | 256 | 81 |
| 1024 | 1,048,576 | 59,049 |
| Version | Recurrence | Time |
|---|---|---|
| four products | $4T(n/2)+O(n)$ | $O(n^2)$ |
| Karatsuba | $3T(n/2)+O(n)$ | $O(n^{\log_2 3})$ |
Three products: both highs, both lows, both sums.
| Step | Method for any exam question |
|---|---|
| 1 | Split at the same m for both numbers. |
| 2 | Find p, q and r. |
| 3 | Middle = r − p − q. |
| 4 | Shift p by 2m and the middle by m, then add. |