Chapter 13: Recursion and divide-and-conquer
Correct recursion rests on two things: a base case that stops it, and an input that gets strictly smaller on every call. Divide-and-conquer is the recursive strategy that pushes this furthest. It splits a problem into independent subproblems, solves them recursively, and combines the results. Unlike dynamic programming, the subproblems do not overlap, so there is nothing to memoize; the payoff instead is that splitting often improves the asymptotics, as merge sort’s improves on the of simple sorts. The Master Theorem tells you exactly when and by how much.
Concepts from other sections (5)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Dynamic programming (DP): solving a problem by breaking it into overlapping subproblems and storing each subproblem’s answer the first time it is computed, which turns an exponential recursion into a polynomial computation. Read more: Chapter 9: Dynamic programming
- Master theorem: for divide-and-conquer recurrences , comparing with gives as , , or , depending on whether the leaves, every level, or the root dominates. Read more: Chapter 12: Discrete Math 2 in Mathematics
- Quickselect: expected-linear selection of the -th element by partitioning, which reorders its input. Read more: 15.4 Heap top-k in C
- Binary search: a search that keeps an interval known to contain the answer and halves it with one comparison per step, taking steps; it needs a monotonic predicate, not necessarily a sorted array. Read more: Chapter 5: Binary search
- Kadane’s algorithm: the maximum-subarray algorithm that tracks the best sum of a subarray ending at the current position, either extending the previous one or starting fresh, along with the best sum seen overall. Read more: Chapter 9: Dynamic programming
This chapter covers the classic split-and-combine template, the merge-sort framework for counting global properties during the merge, quickselect, binary exponentiation, and geometric divide-and-conquer, then states the Master Theorem with worked cases. It ends with two Python examples.
Learning objectives
- Write a divide-and-conquer recursion with a correct base case, split, and combine step.
- Count inversions and similar global properties during merge sort’s merge.
- Find the th smallest element in expected with quickselect.
- Compute in multiplications.
- Solve recurrences of the form with the Master Theorem.
Before you begin
Section titled “Before you begin”You need to be comfortable writing recursive functions and reading big-O notation. Merge sort and binary search, both used here as examples, appear in Binary search; the contrast with overlapping subproblems is developed in Dynamic programming.
The classic template
Section titled “The classic template”Split the range at the midpoint, solve each half, and combine. The base case is a range of one element:
def solve(arr, left, right): if left == right: return base_case(arr[left]) mid = (left + right) // 2 left_result = solve(arr, left, mid) right_result = solve(arr, mid + 1, right) return combine(left_result, right_result)Merge Sort, the divide-and-conquer variant of Maximum Subarray, and Count Inversions all follow it. For maximum subarray, the combine step takes the best of the left answer, the right answer, and the best subarray crossing the midpoint, found by extending outward from mid in both directions.
The merge sort framework
Section titled “The merge sort framework”Some problems need a global property that can be computed during the merge step, while both halves are sorted:
def merge_sort(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 left = merge_sort(arr[:mid]) right = merge_sort(arr[mid:]) return merge(left, right) # counting happens hereCounting inversions is the model case. During the merge, when right[j] < left[i], every remaining element of left (from i to the end) forms an inversion with right[j], so you add len(left) - i in one step instead of counting pairs individually. Sort an Array, Count of Smaller Numbers After Self, Reverse Pairs, and Count Inversions use this framework.
Quickselect
Section titled “Quickselect”To find the th smallest or largest element without sorting, partition around a random pivot and recurse into only the side that contains the answer:
def quickselect(arr, k): pivot = arr[random.randint(0, len(arr)-1)] left = [x for x in arr if x < pivot] mid = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] if k <= len(left): return quickselect(left, k) elif k <= len(left) + len(mid): return pivot else: return quickselect(right, k - len(left) - len(mid))Because only one side is explored, the expected work is . Kth Largest Element in an Array, Top K Frequent Elements, and K Closest Points to Origin are the standard problems.
Binary exponentiation
Section titled “Binary exponentiation”To compute , square the half power instead of multiplying times, which takes multiplications:
def power(x, n): if n == 0: return 1 if n < 0: return 1 / power(x, -n) half = power(x, n // 2) if n % 2 == 0: return half * half else: return half * half * xThe same idea extends to matrix exponentiation (Fibonacci numbers in ) and to modular exponentiation.
Geometric divide-and-conquer
Section titled “Geometric divide-and-conquer”Geometric problems whose brute force is often split cleanly in space. The closest pair of points is the classic:
Sort by x-coordinateSplit into left/right halvesRecursively find closest pair in each halfCheck strip of width 2*min_dist around midlineCombine resultsOnly a constant number of points in the strip need to be compared with each point, so the combine step is linear and the whole algorithm is .
The Master Theorem
Section titled “The Master Theorem”The running time of a divide-and-conquer algorithm that makes recursive calls on inputs of size and does work to split and combine satisfies
The answer depends on how compares with , which measures how fast the number of subproblems grows:
| Condition | Complexity |
|---|---|
Four familiar algorithms show each case:
| Algorithm | Result | |||
|---|---|---|---|---|
| merge sort | 2 | 2 | 1 | |
| binary search | 1 | 2 | 0 | |
| Strassen | 7 | 2 | 2 | |
| Karatsuba | 3 | 2 | 1 |
Strassen and Karatsuba both win by reducing : seven half-size matrix products instead of eight, three half-size integer products instead of four.
Interviewers favor different variants. As a rough guide:
| Company | Favorite variant | Difficulty |
|---|---|---|
| count inversions, closest pair | Hard | |
| Meta | quickselect, merge sort variants | Medium |
| Jane Street | matrix exponentiation | Hard |
| Two Sigma | divide-and-conquer optimization problems | Hard |
| Renaissance | Strassen-style optimizations | Hard |
Key terms
Section titled “Key terms”- Base case: an input on which a recursive function returns directly without calling itself; together with an input that strictly shrinks on every call, it guarantees that the recursion terminates.
- Divide and conquer / divide-and-conquer: an algorithm design that splits a problem into independent subproblems, solves them recursively, and combines their results; unlike dynamic programming the subproblems do not overlap, and the gain comes from better asymptotics, as in merge sort.
- Inversion count: the number of pairs with , computed in during merge sort’s merge by adding the number of remaining left-half elements each time a right-half element is taken first.
- Binary exponentiation / fast exponentiation: computing by squaring and multiplying by once more when is odd, in multiplications; the same idea gives matrix and modular exponentiation.
- Closest pair of points: finding the two nearest points in the plane in by splitting on , solving each half, and checking only a strip around the dividing line, where each point needs comparing with a constant number of others.
In this chapter
Section titled “In this chapter”Both examples are Python programs; run them with python3 11-recursion-divide-conquer/example-1.py and python3 11-recursion-divide-conquer/example-3.py.
- Longest monochromatic tree path: an outline, in Python, of a divide-and-conquer solution for the longest path whose nodes all share a color in a rooted tree.
divideextends the current path when a node has its parent’s color and restarts it otherwise, recurses into every subtree, andconquerjoins the root with its two longest subtree paths (taking only two prevents revisiting nodes). The helper functions are left as stubs to fill in. - Maximum circular subarray: the divide-and-conquer maximum subarray, with the crossing-subarray step that extends left and right from the midpoint, applied to every rotation of the array to find the best circular subarray. Trying all rotations makes it ; Kadane’s algorithm in Dynamic programming can solve the same problem in by also tracking the minimum subarray.