Divide and Conquer
Split the problem, solve the parts, combine the answers.
Merge sort orders a million items with about 20 levels of splitting, where comparing every pair would take half a trillion comparisons. Divide and conquer is that trick in general: split into independent subproblems, solve them recursively, and pay only for combining. Write down the recurrence, and the running time follows.
What you’ll learn
- Write the divide, conquer and combine steps of an algorithm and its recurrence , and solve it with the master theorem.
- Count inversions in time by piggybacking on merge sort, and prove the count correct.
- Solve the maximum subarray problem through its crossing case, and make the combine step by returning summaries.
- Explain when divide and conquer fails (overlapping or unbalanced subproblems, costly combining) and how it exposes parallelism.
- Recognize divide-and-conquer problems: an answer made of a left part, a right part and a part that crosses the split.
The template and its recurrence
A divide-and-conquer algorithm does three things to an input of size : it divides it into subproblems of size about , conquers them recursively (inputs below some size are base cases, solved directly), and combines their answers with extra work. Its running time satisfies the recurrence
The recursion tree reads it off: level holds calls of size , costing in total, and there are about levels.
| Algorithm | Recurrence | Solution |
|---|---|---|
| Binary search, fast exponentiation | worst case | |
| Merge sort, counting inversions | worst case | |
| Maximum subarray, closest pair of points | worst case | |
| Quickselect | one subproblem of random size, plus | expected |
| Karatsuba multiplication | ||
| Strassen matrix multiplication |
The quick way to read a recurrence: going one level down multiplies the level cost by . If that ratio exceeds 1, the costs grow geometrically toward the leaves and the leaves dominate; if it is exactly 1, all levels cost the same; if it is below 1, the top-level combine dominates.
Merge sort and counting inversions
An inversion of an array is a pair of indices with . The number of inversions measures disorder: 0 for a sorted array, for a reversed one. Checking every pair counts them in time, and so, implicitly, does insertion sort, which removes exactly one inversion per shift.
Divide and conquer counts them in . Split into halves and . Every inversion lies inside , inside , or crosses, with in and in . Count the first two recursively. For the crossing pairs, notice that sorting each half does not change them, since it only reorders elements within a half. So let the recursion also return each half sorted, and count the crossing pairs while merging:
def sort_count(a): # returns (sorted copy of a, number of inversions)
if len(a) <= 1:
return a[:], 0
mid = len(a) // 2
left, x = sort_count(a[:mid])
right, y = sort_count(a[mid:])
merged, i, j, cross = [], 0, 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]: # <= keeps equal keys out of the count
merged.append(left[i]); i += 1
else: # right[j] is smaller than all of left[i:]
merged.append(right[j]); j += 1
cross += len(left) - i
merged += left[i:] + right[j:]
return merged, x + y + cross, so in the worst case. When right[j] is output before left[i], it is smaller than left[i] and all the later elements of the sorted left half, which gives exactly len(left) - i crossing inversions with right[j], each counted once.
How many inversions does have?
Show the answer
12
Count, for each element, the later elements smaller than it: 8 has 4 (3, 5, 1, 7), 3 has 1, 12 has 4 (5, 1, 7, 10), 5 has 1, 1 has 0, 14 has 2, 7 has 0. Total 12, out of a possible . In sort_count, the halves and contain 3 and 2 of them, and the top-level merge counts the other 7, the crossing ones.
The crossing case: maximum subarray
The maximum subarray problem asks for the largest sum of a nonempty contiguous block of . Brute force tries all blocks, each in with prefix sums. Divide and conquer: the best block lies in the left half, in the right half, or crosses the middle, and a crossing block is a suffix of the left half followed by a prefix of the right half. So the best crossing block is the best suffix plus the best prefix, found by two scans outward from the middle.
def max_crossing_sum(a, lo, mid, hi): # best a[i:j] with lo <= i < mid < j <= hi
best_left, s = float('-inf'), 0
for i in range(mid - 1, lo - 1, -1): # best suffix of the left half
s += a[i]
best_left = max(best_left, s)
best_right, s = float('-inf'), 0
for j in range(mid, hi): # best prefix of the right half
s += a[j]
best_right = max(best_right, s)
return best_left + best_right
def max_subarray(a, lo=0, hi=None): # best sum of a nonempty a[i:j], lo <= i < j <= hi
if hi is None:
hi = len(a)
if hi - lo == 1:
return a[lo]
mid = (lo + hi) // 2
return max(max_subarray(a, lo, mid), max_subarray(a, mid, hi),
max_crossing_sum(a, lo, mid, hi))Ranges are half-open, . The crossing scans take , so in the worst case.
For , the best block of the left half has sum 5, and so does the best block of the right half . What does max_subarray(a) return?
- 5
- 6
- 10
- 4
Show the answer
B. 6
The best suffix of the left half is and the best prefix of the right half is , so the best crossing block, , sums to 6 and beats both halves.
When it works, when it does not, and parallelism
Divide and conquer pays off under three conditions:
- Independent subproblems. If they overlap, the recursion recomputes them. Plain recursive Fibonacci satisfies , which grows like with ; storing answers (memoization) turns it into dynamic programming.
- Balanced splits. Splitting off a constant amount makes the recursion levels deep: quicksort with a bad pivot satisfies .
- A cheap combine. If combining two halves costs , then : the root dominates, and splitting gained nothing over brute force.
Independent subproblems can also run at the same time. In the fork-join model, the work is the running time on one processor and the span the length of the longest chain of steps that must happen one after another. On processors, a greedy scheduler finishes within (Brent's bound), and Cilk's randomized work stealing achieves in expectation (Blumofe & Leiserson, 1999).
MERGE-SORT(a, lo, hi): # sorts a[lo:hi]
if hi - lo <= 1: return
mid ← ⌊(lo + hi) / 2⌋
spawn MERGE-SORT(a, lo, mid) # the halves are independent:
MERGE-SORT(a, mid, hi) # run them in parallel
sync # wait for both
MERGE(a, lo, mid, hi) # a serial merge: Θ(n) at the topWork . The span satisfies , so the parallelism is only : the serial merge is the bottleneck.
Think first How can the merge itself be parallelized?
Take the middle element of the longer run, find its position in the other run by binary search, put it in its final place, then merge the two left parts and the two right parts in parallel. The merge's span becomes , merge sort's , and the parallelism (Cormen et al., chapter on parallel algorithms).
Recognizing it
Signals. The answer for the whole is assembled from answers for two halves plus something computed across the split: a merge, pairs with one element on each side, a block that straddles the middle, points near a dividing line. "Count the pairs with some property" is a strong hint when the property can be checked across two sorted halves. With up to or , the target is .
| Problem (in our words) | Divide-and-conquer idea | Time |
|---|---|---|
| Count the inversions of an array | count crossing pairs while merging | |
| Count pairs with | before each merge, sweep two pointers across the sorted halves | |
| Count subarrays whose sum lies in | the same on prefix sums: pairs with across the halves | |
| Closest pair of points in the plane | split by ; a closer crossing pair must lie in a strip of width around the line | |
| Merge sorted lists with elements in total | merge the lists in pairs, round after round | |
| Majority element (more than copies) | a majority of the whole is a majority of one half; count both halves' candidates | ; Boyer–Moore voting is |
Key takeaways
- Divide and conquer splits into independent subproblems of size and combines in : . The master theorem compares with , that is, the level ratio with 1.
- Counting inversions rides on merge sort: when an element of the right half is output, add the number of elements still waiting in the left half. worst case.
- Many answers decompose into left, right and crossing parts; for the maximum subarray the crossing part is a best suffix plus a best prefix, and returning summaries makes the combine .
- Divide and conquer needs independent, reasonably balanced subproblems and a cheap combine. Overlapping subproblems call for dynamic programming. Independent halves can run in parallel.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
An algorithm splits an input of size into 4 subproblems of size and combines their answers in time. What is its running time?
Show the answer
A.
Here , , , and : the leaves dominate, and there are of them, so . This is the naive split of -digit multiplication into four half-size products, no faster than the schoolbook method; Karatsuba's trick of three products is what brings the exponent down.
Counting inversions with merge sort: the merge outputs right[j] while left[i], left[i+1], … are still waiting. How many crossing inversions does this add?
jlen(left) - i- 1
len(right) - j
Show the answer
B. len(left) - i
The left half is sorted and right[j] < left[i], so right[j] is smaller than every element still waiting in the left half: len(left) - i elements, each forming one crossing inversion with it. Elements already output from the left half are at most right[j] and form none.
Naive recursive Fibonacci makes 331,160,281 calls to compute , though only 41 distinct values exist. What is the fix?
- Split into halves instead of and
- Run the two recursive calls in parallel
- Add a base case for
- Remember each value the first time it is computed, or fill a table bottom-up: dynamic programming
Show the answer
D. Remember each value the first time it is computed, or fill a table bottom-up: dynamic programming
The subproblems overlap: is needed by both and , and so on down. Divide and conquer treats every call as new; storing each of the 41 values once cuts the work to additions.
Merge sort runs its two recursive calls in parallel but merges sequentially. Its work is . What is its span, the running time on unboundedly many processors?
Show the answer
C.
The span satisfies : the two halves run at the same time, but the top-level merge alone takes . So , and the parallelism, work divided by span, is only . A parallel merge is needed to do better.
Go deeper
- Fast Multiplication: Karatsuba to Strassen · Fewer multiplications by clever splitting, and the race for ω.
- The Fast Fourier Transform · Multiplying polynomials in O(n log n) with roots of unity.
- Divide and Conquer in Geometry · Closest pair of points, convex hulls and their lower bounds.
Further reading
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 4; the maximum-subarray example is §4.1 of the 3rd edition (2009).
- J. Kleinberg & É. Tardos, Algorithm Design (Addison-Wesley, 2005), chapter 5.
- J. Erickson, Algorithms (2019), chapter 1.
- J. Bentley, "Programming pearls: algorithm design techniques," Communications of the ACM 27(9) (1984), 865–873.