Divide and Conquer
Split the problem, solve the pieces, stitch the answers together — and how to count the cost.
- write and solve recurrences for recursive algorithms (recursion tree, master theorem)
- implement fast exponentiation and count inversions
- explain quickselect and median of medians
- see why fewer recursive calls beats doing less work per call
Divide and conquer
Many problems yield to the same three-step recipe:
The divide-and-conquer recipe
You have already met it: merge sort (divide = split in half, combine = merge) and quicksort (divide = partition, combine = nothing) and binary search (discard half). This week we learn how to analyse such algorithms and meet new applications.
Recurrences: the cost of a recursive algorithm
If an algorithm splits a size-n problem into a subproblems of size n/b and spends f(n) on dividing and combining, its running time satisfies the recurrence
T(n) = a · T(n/b) + f(n)
| Algorithm | Recurrence | Solution |
|---|---|---|
| Binary search | T(n) = T(n/2) + 1 | Θ(log n) |
| Merge sort | T(n) = 2T(n/2) + n | Θ(n log n) |
| Quicksort, balanced splits | T(n) = 2T(n/2) + n | Θ(n log n) |
| Quicksort, worst case | T(n) = T(n−1) + n | Θ(n²) |
| Naive Fibonacci | T(n) = T(n−1) + T(n−2) + 1 | Θ(φⁿ) ≈ 1.618ⁿ |
| Karatsuba multiplication | T(n) = 3T(n/2) + n | Θ(n^1.585) |
Unrolling a recursion tree
Draw the calls as a tree. For T(n) = 2T(n/2) + n: level 0 does n work, level 1 has two calls each doing n/2 — again n in total — and so on. There are log₂ n levels, each costing n, so the total is n log₂ n.
For T(n) = a·T(n/b) + n^d, compare a with b^d:
a < b^d→ the top level dominates: Θ(n^d)a = b^d→ every level costs the same: Θ(n^d log n)a > b^d→ the leaves dominate: Θ(n^(log_b a))
Which case of the master theorem applies to T(n) = 2T(n/2) + n?
Using the master theorem, solve T(n) = 4T(n/2) + n. What exponent k is in Θ(n^k)?
What does this print? (type the exact output)
def T(n):
return 1 if n <= 1 else 2 * T(n // 2) + n
print(T(8))Fast exponentiation
Computing xⁿ by multiplying n − 1 times is O(n). Divide and conquer: xⁿ = (x^(n/2))² for even n, and x · x^(n−1) for odd n. Each step halves the exponent: O(log n) multiplications.
Writing power(x, n//2) * power(x, n//2) makes two calls per level: T(n) = 2T(n/2) + 1 = Θ(n) — all the benefit lost. Store the result in a variable.
About how many multiplications does fast exponentiation need to compute x¹⁰⁰⁰⁰⁰⁰?
Counting inversions
How different are two rankings? Say you and a friend rank 5 films. An inversion is a pair of items in the wrong relative order: positions i < j with A[i] > A[j]. The number of inversions measures how far from sorted a list is (0 = sorted, n(n−1)/2 = reversed). Counting all pairs is O(n²). Merge sort counts them in O(n log n).
When merging two sorted halves L and R: if we take an element from R while k elements remain in L, it jumps ahead of exactly those k larger elements — that is k cross inversions. Add them up during the merge.
How many inversions does [3, 1, 2] have?
A = [3, 1, 2] print(sum(1 for i in range(len(A)) for j in range(i + 1, len(A)) if A[i] > A[j]))
The maximum number of inversions in a list of n distinct items is…
Selection: the k-th smallest element
Sorting finds the median in O(n log n). Can we do better? Quickselect partitions around a pivot like quicksort but recurses into only the side that contains the k-th item.
With a good pivot (always near the middle) the sizes go n, n/2, n/4, … so total work is n + n/2 + … = 2n = O(n). With a bad pivot it is O(n²). A random pivot gives expected O(n).
Median of medians — a guaranteed good pivot
Split the list into groups of 5, find each group's median (constant time per group), then recursively find the median of those medians and use it as pivot. This pivot is guaranteed to have at least ~30% of the elements on each side, so the recurrence is T(n) ≤ T(n/5) + T(7n/10) + O(n), which solves to Θ(n) worst case.
Quickselect with a random pivot runs in expected time…
Why is the median-of-medians pivot special?
What does this print?
def kth(L, k):
p = L[0]
lo = [x for x in L if x < p]
eq = [x for x in L if x == p]
hi = [x for x in L if x > p]
if k <= len(lo): return kth(lo, k)
if k <= len(lo) + len(eq): return p
return kth(hi, k - len(lo) - len(eq))
print(kth([9, 3, 7, 1, 5], 2), kth([9, 3, 7, 1, 5], 5))Multiplying big numbers
The schoolbook method multiplies two n-digit numbers in n² digit operations. Split x = a·10^h + b and y = c·10^h + d. Then xy = ac·10^(2h) + (ad + bc)·10^h + bd needs four half-size products. Karatsuba noticed ad + bc = (a + b)(c + d) − ac − bd, so three products suffice: T(n) = 3T(n/2) + n = Θ(n^1.585).
Karatsuba improves on the schoolbook method by…
Chapter challenge — Week 8
Merge sort's recurrence is…
What does this print? (type the exact output)
def inv(A):
return sum(1 for i in range(len(A)) for j in range(i + 1, len(A)) if A[i] > A[j])
print(inv([4, 3, 2, 1]))Solve T(n) = 8T(n/2) + n² with the master theorem.
Counting inversions with merge sort.
How many multiplications of big numbers does one Karatsuba step use?
Why does power(x, n//2) * power(x, n//2) destroy the speed-up?
Which are divide-and-conquer algorithms?
Quickselect's expected time is O(n), but sorting needs…
Practice on LeetCode
Divide and conquer, recurrences, selection and counting inversions.
Try each problem first with a brute-force idea and estimate its cost, then improve it using this chapter's technique. Links open LeetCode in a new tab; all problems listed are free. Levels follow LeetCode's own labels.
| Problem | Level | Practises | |
|---|---|---|---|
| Pow(x, n) ↗ | Medium | fast exponentiation: O(log n) | |
| Majority Element ↗ | Easy | divide and conquer (also Boyer–Moore voting) | |
| Maximum Subarray ↗ | Medium | try the divide-and-conquer solution, then Kadane | |
| Sort an Array ↗ | Medium | merge sort | |
| Kth Largest Element in an Array ↗ | Medium | quickselect | |
| Different Ways to Add Parentheses ↗ | Medium | split at each operator, combine the results | |
| Multiply Strings ↗ | Medium | big-number multiplication | |
| Count of Smaller Numbers After Self ↗ | Hard | merge-sort counting, like inversions | |
| Reverse Pairs ↗ | Hard | inversion counting during merge | |
| Median of Two Sorted Arrays ↗ | Hard | binary search / divide and conquer |
Key takeaways
- Divide, conquer recursively, combine. The running time is captured by a recurrence like
T(n) = a·T(n/b) + f(n). - Master theorem for
a·T(n/b) + n^d: compareawithb^d→ Θ(n^d), Θ(n^d log n) or Θ(n^(log_b a)). - Fast exponentiation: O(log n). Counting inversions: O(n log n) by piggybacking on merge sort.
- Quickselect finds the k-th smallest in expected O(n); median-of-medians makes it worst-case O(n).
- Karatsuba trades four sub-multiplications for three: Θ(n^1.585).