Divide and Conquer (DSA #24)
The fastest algorithms in this course share a shape: split the problem in half, solve each half, combine the results. Merge sort, binary search, quickselect, and the fast Fourier transform all follow it. Divide and conquer turns an \(O(n^2)\) problem into \(O(n \log n)\) not by clever tricks but by reducing the problem size at every level of a recursion tree — and the tree is usually shallow enough that the total work is dominated by the top level.
This chapter covers the pattern, the recurrence that describes its cost, the master theorem for solving that recurrence, and the standard problems.
The pattern
Three steps:
- Divide the input into smaller subproblems (usually halves).
- Conquer each subproblem recursively.
- Combine the subproblem answers into the answer.
When the subproblems are independent (no overlap), this is divide and conquer. When they overlap, the same shape becomes dynamic programming (Chapter 26) — the distinction matters.
def divide_and_conquer(problem):
if problem is small: # base case
return solve_directly(problem)
left, right = split(problem) # divide
a = divide_and_conquer(left) # conquer
b = divide_and_conquer(right) # conquer
return combine(a, b) # combine
Binary search: halve and discard
The simplest divide and conquer: compare against the middle and recurse into exactly one half. Because only one branch is taken, the recursion is a path, not a tree, and the cost is the depth: \(O(\log n)\).
def binary_search(a, target, lo=0, hi=None):
if hi is None: hi = len(a) - 1
if lo > hi: return -1
mid = (lo + hi) // 2
if a[mid] == target: return mid
if a[mid] < target: return binary_search(a, target, mid + 1, hi)
return binary_search(a, target, lo, mid - 1)
Merge sort: halve, sort, merge
Both halves are solved and the answers combined by merging (Chapter 7). The recursion tree has \(\log n\) levels, and each level does \(O(n)\) total work merging.
def merge_sort(a):
if len(a) <= 1:
return a
mid = len(a) // 2
left, right = merge_sort(a[:mid]), merge_sort(a[mid:])
return merge(left, right)
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, minimum width=1.3cm, minimum height=0.45cm, font=\small\ttfamily},
a/.style={->, thick}]
\node[n, fill=orange!20] (r) at (0,0) {n};
\node[n, fill=blue!10] (l) at (-1.6,-0.8) {n/2}; \node[n, fill=blue!10] (rr) at (1.6,-0.8) {n/2};
\node[n, fill=green!14] (ll) at (-2.4,-1.6) {n/4}; \node[n, fill=green!14] (lr) at (-0.8,-1.6) {n/4};
\node[n, fill=green!14] (rl) at (0.8,-1.6) {n/4}; \node[n, fill=green!14] (rrr) at (2.4,-1.6) {n/4};
\draw[a] (r) -- (l); \draw[a] (r) -- (rr);
\draw[a] (l) -- (ll); \draw[a] (l) -- (lr);
\draw[a] (rr) -- (rl); \draw[a] (rr) -- (rrr);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-2.1) {$\log n$ levels, $O(n)$ work per level};
\end{tikzpicture}
Quickselect: find the k-th smallest
Sorting to find one element is wasteful. Quickselect partitions once (as quick sort does) and recurses into only the side containing the \(k\)-th element — the other side is discarded. Expected \(O(n)\), worst \(O(n^2)\) with a bad pivot.
import random
def quickselect(a, k):
if not a:
return None
pivot = random.choice(a)
left = [x for x in a if x < pivot]
mid = [x for x in a if x == pivot]
right = [x for x in a if x > pivot]
if k < len(left):
return quickselect(left, k)
if k < len(left) + len(mid):
return pivot
return quickselect(right, k - len(left) - len(mid))
print(quickselect([7, 10, 4, 3, 20, 15], 2)) # 3rd smallest = 7
This is the same partition idea as quick sort, but by discarding half the data it avoids the full \(O(n \log n)\). It is the standard answer to “k-th largest element” when a heap (Chapter 11) is not required.
Other standard problems
- Closest pair of points — sort by x, divide, and check a narrow strip near the split line for a closer pair; \(O(n \log n)\) versus \(O(n^2)\) brute force.
- Maximum subarray — divide, and combine by considering the crossing subarray at the midpoint; \(O(n \log n)\) (Kadane’s algorithm gets \(O(n)\)).
- Fast exponentiation — compute \(x^n\) by halving the exponent, \(O(\log n)\) multiplications.
- Karatsuba multiplication, Strassen matrix multiply, FFT — famous divide-and-conquer wins that beat the naive bounds.
def power(x, n):
if n == 0: return 1
half = power(x, n // 2)
return half * half * (x if n % 2 else 1) # O(log n)
The master theorem: solving the recurrence
A divide-and-conquer cost has the form
\[ T(n) = a\,T(n/b) + f(n) \]
where \(a\) is the number of subproblems, \(n/b\) their size, and \(f(n)\) the divide/combine cost. Compare \(f(n)\) with \(n^{\log_b a}\):
- If \(f(n) = O(n^{\log_b a - \epsilon})\), the leaves dominate: \(T(n) = \Theta(n^{\log_b a})\).
- If \(f(n) = \Theta(n^{\log_b a})\), every level contributes equally: \(T(n) = \Theta(n^{\log_b a} \log n)\).
- If \(f(n) = \Omega(n^{\log_b a + \epsilon})\), the top dominates: \(T(n) = \Theta(f(n))\).
For merge sort, \(a = 2\), \(b = 2\) gives \(n^{\log_2 2} = n\), matching \(f(n) = O(n)\); so \(T(n) = \Theta(n \log n)\). For binary search, \(a = 1\), \(b = 2\) gives \(n^0 = 1\), and \(f(n) = O(1)\); so \(T(n) = \Theta(\log n)\).
Divide and conquer vs dynamic programming
Both break problems into subproblems. The difference is overlap:
- Subproblems are independent (each solved once) → divide and conquer.
- Subproblems repeat → dynamic programming, which caches to avoid redoing them.
Merge sort’s halves never overlap; naive Fibonacci’s branches overlap heavily (Chapter 26).
Pitfalls
- Unbalanced splits. Dividing \(n\) into \(1\) and \(n-1\) gives a linear-depth tree and \(O(n^2)\); aim for balanced splits.
- Expensive combine. A combining step of \(O(n^2)\) can erase the log-factor gains; the combine must be efficient (often linear).
- Missing the base case. Every recursion needs one; forgetting it recurses forever.
- Copying whole subarrays. Slicing allocates; in performance-critical code, pass indices into the original array.
- Confusing it with DP. Overlapping subproblems without memoisation cause exponential rework; cache them.
- Assuming the master theorem always applies. It requires the regular form; other recurrences need other methods.
What is the recurrence for merge sort, and what does the master theorem conclude? What distinguishes divide and conquer from dynamic programming?
ASolution
Merge sort is \(T(n) = 2T(n/2) + O(n)\); the master theorem gives \(\Theta(n \log n)\) because the combine cost matches \(n^{\log_2 2} = n\). Divide and conquer applies when subproblems are independent (each solved once); dynamic programming applies when the same subproblems recur, caching results to avoid recomputation.
Next: Greedy Algorithms (DSA #25) — when taking the locally best choice is globally optimal.