Sub topic 1
What Divide and Conquer Means: Divide, Conquer, Combine
Divide and conquer is a way to design algorithms. You split a problem into smaller problems of the same kind, solve each one recursively, and then build the answer to the original problem from their answers. Many fast algorithms follow this pattern, including binary search, merge sort, quicksort, and Karatsuba multiplication. Once you can see the three steps in an algorithm, you can reason about whether it is correct and how fast it runs.
This chapter defines the pattern and names its parts. It also shows the main design choices and the mistakes people often make. Later chapters cover base cases, correctness proofs, and running-time analysis in detail.
Prerequisites
This chapter assumes you can already:
- Read and write basic Python: functions, lists, loops, and integer division with
//. - Write and trace a recursive function, and know what a call stack is.
- Read Big-O notation, such as O(n), O(log n), and O(n log n).
- Work with list indices and half-open ranges like
a[lo:hi].
Proof by induction helps, but you won't need it until the correctness chapter.
The Three Steps
Every divide-and-conquer algorithm has three steps:
- Divide. Break the problem into one or more subproblems. Each subproblem is a smaller instance of the same problem.
- Conquer. Solve each subproblem by calling the same algorithm recursively. If a subproblem is small enough, solve it directly. That direct case is the base case.
- Combine. Merge the subproblem solutions into a solution for the original problem.
"Same kind" is the key requirement. A subproblem of "sort this list" must be "sort this smaller list", not some other task. That is what lets one function call itself.
A First Example: Maximum of a Range
Finding the largest element of a list doesn't need divide and conquer, because a single loop already does it in O(n). It still makes a good first example, because each of the three steps is easy to see.
def range_max(a, lo, hi):
# Largest element of a[lo:hi]; requires hi - lo >= 1
if hi - lo == 1: # base case: one element
return a[lo]
mid = (lo + hi) // 2 # divide: split the range in half
left = range_max(a, lo, mid) # conquer: left half
right = range_max(a, mid, hi) # conquer: right half
return max(left, right) # combine: compare two answers
nums = [4, 17, 3, 9, 21, 8, 5, 12]
print(range_max(nums, 0, len(nums))) # 21Here is each step in this code:
- Divide computes
midand splits[lo, hi)into[lo, mid)and[mid, hi). Both halves are non-empty whenever the range has at least two elements. - Conquer makes two recursive calls, one per half.
- Combine is one comparison. The largest element of the whole range is the larger of the two halves' maximums.
The function passes indices instead of slicing with a[lo:mid]. Slicing copies elements, which adds O(n) work at every level of recursion. Passing indices keeps the divide step at O(1).
A Generic Template
The pattern is regular enough to write as a higher-order function. Real code almost never looks like this, but the template makes the parts explicit.
def divide_and_conquer(problem, is_small, solve_directly, divide, combine):
if is_small(problem):
return solve_directly(problem)
subproblems = divide(problem)
solutions = [
divide_and_conquer(p, is_small, solve_directly, divide, combine)
for p in subproblems
]
return combine(problem, solutions)
# Sum of a list, expressed through the template
total = divide_and_conquer(
[3, 1, 4, 1, 5, 9, 2, 6],
is_small=lambda xs: len(xs) <= 1,
solve_directly=lambda xs: xs[0] if xs else 0,
divide=lambda xs: [xs[:len(xs) // 2], xs[len(xs) // 2:]],
combine=lambda xs, sols: sum(sols),
)
print(total) # 31Designing a new divide-and-conquer algorithm means filling in these five pieces: the size test, the direct solution, the split, the recursion, and the combine. The hard part is usually one piece, and which piece it is depends on the problem.
Where the Work Goes
Algorithms differ in which step does the real work. The table compares the classic algorithms covered in later chapters.
| Algorithm | Divide | Number of subproblems | Combine | Where the work is |
|---|---|---|---|---|
| Binary search | Compare with middle, pick one half | 1 | Nothing | Divide (trivial) |
| Merge sort | Split at the midpoint | 2 | Merge two sorted lists, O(n) | Combine |
| Quicksort | Partition around a pivot, O(n) | 2 | Nothing (concatenate in place) | Divide |
| Maximum subarray | Split at the midpoint | 2 | Compute best crossing slice, O(n) | Combine |
| Fast exponentiation | Halve the exponent | 1 (reused) | One or two multiplications | Combine (small) |
| Karatsuba | Split numbers into high and low halves | 3 | Shifts and additions, O(n) | Fewer subproblems |
Two patterns show up in the table:
- Easy split, hard combine. Merge sort splits blindly and pays for it when merging.
- Hard split, easy combine. Quicksort puts in effort before recursing so the results need no merging.
Algorithms with a single subproblem, such as binary search and fast exponentiation, are sometimes called decrease and conquer. They follow the same three-step pattern with one recursive call, which makes them much cheaper.
Three Properties a Good Decomposition Needs
- Subproblems are strictly smaller. Each recursive call must move toward the base case. If a split can produce a piece the same size as the input, for example
mid = hion a two-element range, the recursion never ends. - Subproblems are independent. The halves of merge sort share no elements, so each half is solved once. When subproblems overlap and the same ones are solved repeatedly, plain recursion wastes exponential time. That is the territory of dynamic programming, which a later chapter covers.
- Combining is cheaper than solving. If combining two halves costs as much as solving the whole problem directly, splitting buys nothing. The speedup comes from a cheap combine applied over a shallow recursion tree.
Common Errors
- Unbalanced splits. Splitting n items into pieces of n − 1 and 1 is still divide and conquer, but the recursion depth becomes n instead of log n. Quicksort with a bad pivot falls into this case and degrades to O(n²).
- Hidden copying. Slicing lists in Python adds O(n) work per call. In merge sort this cost is absorbed by the O(n) merge. In binary search it would raise O(log n) to O(n).
- Off-by-one ranges. Mixing inclusive
[lo, hi]and half-open[lo, hi)conventions in one function causes skipped elements and infinite loops. Pick one convention and keep to it. - Missing or wrong base case. An empty range or a single element must be handled before dividing. The next chapter is about this.
Exercises
Exercise
You want to count how many elements of a list are negative using divide and conquer. Describe the divide, conquer, and combine steps, and give the base case.
Show answer
Divide: split the index range [lo, hi) at mid = (lo + hi) // 2. Conquer: recursively count negatives in [lo, mid) and [mid, hi). Combine: add the two counts. Base case: a range of one element returns 1 if that element is negative and 0 otherwise. An empty range, which you can handle as a guard, returns 0.
Exercise
A student writes rangemax with mid = (lo + hi + 1) // 2 and the recursive calls rangemax(a, lo, mid) and range_max(a, mid, hi). The base case is unchanged. Does the function still work for every range of length at least 1? Explain.
Show answer
Yes. For a range of length k >= 2, mid = lo + ceil(k/2). That gives lo < mid < hi, because ceil(k/2) is between 1 and k - 1 when k >= 2. Both halves are non-empty and strictly smaller, so the recursion still reaches the length-1 base case. Only the split shifts: the left half now gets the extra element when the length is odd.
Exercise
Why does passing indices instead of slices matter more for binary search than for merge sort?
Show answer
Binary search does O(1) work per level over O(log n) levels. Slicing adds O(n) copying at the top level, and the costs n + n/2 + n/4 + ... sum to O(n), which ruins the O(log n) bound. Merge sort already does O(n) merge work per level, so copying adds only a constant factor and the O(n log n) bound stays the same.