Sub topic 3
Proving Divide-and-Conquer Algorithms Correct
A divide-and-conquer algorithm calls itself on smaller inputs, so its correctness depends on its own correctness at smaller sizes. That might look circular. Strong induction is the tool that removes the circularity. This chapter gives you a proof template that fits almost every algorithm in the rest of the tutorial and shows the mistakes that most often make these proofs fail.
This chapter assumes you can write and trace recursive functions, that you have seen proof by induction at least once, and that you have read the previous chapter on base cases and termination.
Why Strong Induction Fits Recursion
Ordinary induction proves a statement P(n) by showing P(1) holds and that P(n − 1) implies P(n). Divide-and-conquer algorithms rarely shrink the input by exactly one. Merge sort turns an input of size n into inputs of size ⌊n/2⌋ and ⌈n/2⌉. Binary search keeps about half the range. To cover these cases you need strong induction, where you assume P(k) for every k smaller than n, not only for n − 1.
The two ideas line up step by step:
| Recursive algorithm | Strong induction proof |
|---|---|
| Base case returns an answer directly | Base case: prove P holds for the smallest sizes |
| Divide step creates smaller subproblems | Show every subproblem has size strictly less than n and at least the base size |
| Recursive calls solve the subproblems | Inductive hypothesis: those calls return correct answers |
| Combine step builds the final answer | Show that correct sub-answers combine into a correct answer |
The Proof Template
- State P(n) precisely. Say exactly what "correct" means for every valid input of size n. Vague statements such as "the function works" cannot be proved.
- Prove the base cases. Cover every size the algorithm handles without recursing.
- Inductive step. Fix n larger than the base sizes and assume P(k) for all valid k < n.
- Show each recursive call receives a valid input whose size is strictly less than n.
- Apply the hypothesis to conclude each call returns a correct result.
- Prove that the combine step turns correct sub-results into a correct result for size n.
The middle bullet is where termination and correctness meet. If a subproblem is not strictly smaller, you cannot apply the hypothesis, and the recursion may not stop.
A Worked Example: Recursive Maximum
def rec_max(a, lo, hi):
# Returns the largest element of the non-empty slice a[lo:hi]
if hi - lo == 1:
return a[lo]
mid = (lo + hi) // 2
left = rec_max(a, lo, mid)
right = rec_max(a, mid, hi)
return left if left >= right else right
data = [4, 17, -3, 9, 17, 2]
print(rec_max(data, 0, len(data))) # 17Claim. For every n ≥ 1, let P(n) be the statement: for every list a and indices with hi - lo == n, rec_max(a, lo, hi) returns max(a[lo], …, a[hi − 1]).
Base case (n = 1). The slice has one element, a[lo], and the function returns it. That element is the maximum.
Inductive step. Let n ≥ 2 and assume P(k) for all 1 ≤ k < n. Set mid = ⌊(lo + hi)/2⌋.
- Subproblem sizes. The left size is mid − lo = ⌊n/2⌋ and the right size is hi − mid = ⌈n/2⌉. For n ≥ 2, both are at least 1 and at most n − 1. So both calls get valid, strictly smaller inputs.
- Hypothesis. By P(⌊n/2⌋) and P(⌈n/2⌉),
leftis the maximum of a[lo:mid] andrightis the maximum of a[mid:hi]. - Combine. The two slices together cover a[lo:hi] with no gaps or overlap. Any element of a[lo:hi] lies in one of them, so it is at most
leftor at mostright, and therefore at most the larger of the two. The returned value is itself an element of the slice. An element of the set that is at least every element is the maximum.
By strong induction, P(n) holds for all n ≥ 1. ∎
Notice how much of the proof concerns the divide step's arithmetic. The claim "both halves are non-empty and smaller" is the part that breaks most often in real code.
How Proofs Expose Bugs
Here is a version that uses a closed range [lo, hi] and rounds the midpoint up:
def bad_max(a, lo, hi):
# Intended: largest element of a[lo..hi] inclusive
if lo == hi:
return a[lo]
mid = (lo + hi + 1) // 2 # rounds up
left = bad_max(a, lo, mid) # a[lo..mid]
right = bad_max(a, mid + 1, hi) # a[mid+1..hi]
return max(left, right)
try:
bad_max([3, 8], 0, 1)
except RecursionError:
print("RecursionError: the subproblem did not shrink")Try to write the size check from the template. For a range of two elements, lo = 0 and hi = 1, so mid = 1. The left call gets [0, 1], which is the same size as the original. The hypothesis does not apply, and in practice the function recurses until Python stops it. The proof attempt locates the bug before any test does. The fix is either to round down (mid = (lo + hi) // 2) or to split as [lo, mid − 1] and [mid, hi].
Combine Steps with Loops Need Loop Invariants
In rec_max the combine step is a single comparison. In merge sort, maximum subarray, and closest pair, the combine step is a loop, and proving it correct is a separate argument inside the inductive step. The usual tool is a loop invariant: a statement that is true before the loop, stays true after each iteration, and gives the desired result when the loop exits.
For the merge step that the merge sort chapter builds, a suitable invariant is: "out holds the len(out) smallest elements of left + right, in sorted order, and they are exactly left[:i] + right[:j]." You prove it holds initially (everything is empty), that taking the smaller front element keeps it true, and that when one list runs out, appending the rest of the other list keeps it true. The outer induction then uses this result as its combine proof.
Common Errors in These Proofs
| Error | What goes wrong | Fix |
|---|---|---|
| Using ordinary induction | Hypothesis covers only n − 1, but calls use n/2 | Assume P(k) for all k < n |
| Proving only for powers of two | Odd sizes split unevenly and may hit untested cases | Use ⌊n/2⌋ and ⌈n/2⌉ explicitly |
| Missing a base size | Some input reaches a size that neither the base nor the split handles, such as n = 0 | List every size that does not recurse and prove each |
| Vague P(n) | You cannot tell what the combine step must prove | State the output exactly in terms of the input |
| Skipping the combine proof | Correct sub-results are assumed to combine correctly | Prove the combine step, using a loop invariant if it has a loop |
| Hypothesis applied to invalid inputs | A subproblem violates a precondition, such as an empty or unsorted slice | Check that every precondition carries over to the subproblems |
Exercises
Exercise
In the proof for rec_max, why is it necessary that n ≥ 2 in the inductive step? What would fail if the inductive step tried to cover n = 1?
Show answer
For n = 1, mid − lo = ⌊1/2⌋ = 0, so the left subproblem would be empty, which P does not cover, and the right subproblem would have size 1, which is not smaller than n. The hypothesis could not be applied to either call. That is why n = 1 is handled as a base case and the inductive step starts at n = 2, where both halves have sizes between 1 and n − 1.
Exercise
A function sums a[lo:hi] by returning 0 when hi - lo == 0 and otherwise returning a[lo] + rec_sum(a, lo + 1, hi). Write P(n) and state which form of induction is enough.
Show answer
P(n): for every list a and indices with hi − lo = n ≥ 0, rec_sum(a, lo, hi) returns a[lo] + … + a[hi − 1], with the empty sum equal to 0. Ordinary induction is enough because the only recursive call has size n − 1. The base case is n = 0. In the step, by P(n − 1) the call returns the sum of a[lo+1:hi], and adding a[lo] gives the sum of a[lo:hi].
Exercise
A student proves a divide-and-conquer algorithm correct only for n = 2^k, using induction on k. Give a concrete way an algorithm can pass that proof yet fail on other inputs.
Show answer
The split arithmetic can be wrong only for odd sizes. For example, a split into [lo, lo + n//2) and [lo + n//2 + 1, hi) skips one element when n is odd, but that element is still skipped when n is even, so consider instead [lo, mid) and [mid, lo + 2*(mid − lo)). That split covers the range exactly when n is even and drops the last element when n is odd. Every power of two above 1 is even at every level, so the power-of-two proof never sees the dropped element. A proof using ⌊n/2⌋ and ⌈n/2⌉ for every n would catch it.
Exercise
Write the loop invariant you would use to prove that the merge step returns a sorted list containing exactly the elements of left and right, assuming both are sorted.
Show answer
Before each iteration: out equals left[:i] + right[:j] rearranged in sorted order, and every element of out is ≤ every element of left[i:] and right[j:]. It holds initially because all three are empty. Appending the smaller of left[i] and right[j] keeps it true because that element is ≤ everything remaining, since both lists are sorted. When the loop ends, one list is used up, and extending out with the sorted remainder of the other keeps out sorted and makes it contain every element.