The Divide and Conquer Scheme
Divide and conquer is one of the oldest and most powerful strategies for designing algorithms. Instead of attacking a problem as a whole, it breaks it into smaller problems of the same kind, solves them (usually by applying the same strategy again), and combines their solutions. We have already met two examples: binary search, which discards half of the array at each step, and Quicksort, which partitions the array and sorts each part.
This lesson presents the general scheme, what we need to apply it, and its two main variants. The following lessons show how to analyze the complexity of these algorithms and apply the paradigm to many classic problems.
- The three steps of divide and conquer and the three ingredients needed to apply it.
- The difference between division and subtraction schemes, and what reduction means.
- How to analyze the complexity of a divide and conquer algorithm with recurrences and the general formulas for both schemes.
- Many classic applications: factorial, sum of a vector, searching, Fibonacci, greatest common divisor, Mergesort, Quicksort, the Towers of Hanoi, the multiplication of large integers, the tennis tournament, the Tromino puzzle, and the majority element, mode and median problems.
A Story: Santa's Dirty Socks
The short film Santa's Dirty Socks tells the story perfectly. It is ten to midnight on Christmas Eve, and 1,024 boxes are ready to be loaded on the sleigh. Then Mrs. Christmas discovers that Santa's dirty socks have been wrapped in one of the boxes by mistake. Unwrapping every box would take far too long.
Santa has a big pair of scales, and all the presents weigh the same, except the one with the socks. The first idea is to weigh the boxes one against another, which could take hundreds of comparisons. Then a little elf has a better idea: put half of the boxes on each side of the scales; the side with the socks is heavier, so the other half can be dismissed. Now there are 512 suspicious boxes. Repeat: 256, 128, 64, 32, 16, 8, 4, 2... and on the tenth weighing, the box with the socks is found.
The elf has just applied divide and conquer: each weighing reduces the problem to one of half the size, and weighings are enough. With a million boxes, 20 weighings would suffice.
The Scheme
Divide and conquer obtains the solution of a problem in three steps:
- Divide (decompose) the problem into several subproblems of the same kind, but smaller than the original.
- Conquer (solve) each subproblem:
- in the general case, recursively, applying the same scheme;
- in the base case (when the subproblem is small enough), directly, with a simple method.
- Combine the solutions of the subproblems to obtain the solution of the original problem.
What do we need?
To apply divide and conquer to a problem, we need three ingredients:
- A recursive scheme that reduces the original problem to smaller instances of itself, eventually reaching the base case.
- A simple algorithm capable of solving the base cases, which must be efficient for small instances.
- A method to combine the results of the subproblems into the solution of the original problem.
The general pseudocode
SolutionType divideAndConquer(ProblemType problem) {
if (problem is sufficiently small)
return solveTrivialCase(problem); // base case
ProblemType[] subproblems = decompose(problem); // divide
SolutionType[] subsolutions = new SolutionType[subproblems.length];
for (int i = 0; i < subproblems.length; i++)
subsolutions[i] = divideAndConquer(subproblems[i]); // conquer
return combine(subsolutions); // combine
}
Not every algorithm has all the steps explicitly. In binary search, "combining" is trivial: the solution of the only subproblem is the solution of the problem. In Quicksort, all the work is done when dividing (partitioning), and combining does nothing. In Mergesort, dividing is trivial (compute the middle), and the work is done when combining (merging).
Division and Subtraction
The efficiency of a divide and conquer algorithm depends crucially on how much each subproblem shrinks. There are two families:
- Division: each subproblem has a size that is a fraction of the original, (for example, half). The size decreases very quickly: after about levels, the subproblems are trivial. Binary search, Mergesort and Quicksort (in its good cases) are of this type.
- Subtraction: each subproblem has a size that is a constant amount smaller than the original, (for example, ). The size decreases slowly: about levels are needed. The recursive factorial, , is of this type.
The other important parameter is the number of subproblems, . When (a single subproblem), the process is sometimes called reduction, because the problem is simply reduced to a smaller instance of itself, as in binary search or the factorial.
The next lesson shows how to compute the complexity of both families. The intuition is this:
- Division is usually efficient: few levels of recursion.
- Subtraction with gives polynomial algorithms, but with a recursion depth proportional to .
- Subtraction with is dangerous: the number of calls grows exponentially. The naive recursive Fibonacci, , is the classic example.
🧠 Checkpoint: Division or subtraction?
Question: Classify each algorithm as division or subtraction, and give its number of subproblems : binary search, the recursive factorial, Mergesort and the naive recursive Fibonacci.
Answer: Binary search: division, (a reduction). Factorial: subtraction, (a reduction). Mergesort: division, . Naive Fibonacci: subtraction, , the dangerous combination that leads to exponential algorithms.
Worth Noting
- The number of subproblems, , should be small. Every additional subproblem multiplies the work.
- The subproblems should be independent, and ideally of similar size. If the same subproblems appear again and again (as in Fibonacci), divide and conquer repeats work, and another technique (dynamic programming) is more suitable.
- The recursive design is usually clearer and more elegant. Divide and conquer algorithms are often short and easy to justify: if the subproblems are solved correctly and the combination is correct, the whole algorithm is correct (a proof by induction).
- The same can be done with an iterative loop, especially in the case of reduction (). Binary search, the factorial and the sum of a vector have simple iterative versions that avoid the overhead of recursive calls and, above all, the use of the call stack.
Each recursive call occupies a frame on the call stack. A subtraction scheme with has a recursion depth proportional to : for example, summing a vector of 100,000 elements with sum(i) = v[i] + sum(i + 1) ends with a StackOverflowError in a Java virtual machine with the default stack size. A division scheme over the same vector only reaches a depth of about . When a subtraction scheme with a single subproblem would recurse deeply, prefer an iterative version.
A First Example: Three Ways of Summing a Vector
The sum of the elements of a vector, which we analyzed in the first chapter, can be solved iteratively or with divide and conquer, both by subtraction and by division:
// Iterative: O(n) time, O(1) extra memory
public int sumIterative(int[] v) {
int accumulator = 0;
for (int i = 0; i < v.length; i++)
accumulator += v[i];
return accumulator;
}
// Subtraction (a = 1, b = 1): the sum of the elements from position i
// is v[i] plus the sum of the elements from position i + 1
private int sumBySubtraction(int i, int[] v) {
if (i == v.length) return 0; // base case: no elements
return v[i] + sumBySubtraction(i + 1, v);
}
// Division (a = 2, b = 2): the sum of a part is the sum of its two halves
private int sumByDivision(int left, int right, int[] v) {
if (left == right) return v[left]; // base case: one element
int mid = left + (right - left) / 2;
return sumByDivision(left, mid, v) + sumByDivision(mid + 1, right, v);
}
With 4 5 6 1 3 2 7 8, the division version computes and , then :
All three versions are : every element must be added once. They differ in their recursion depth (, and , respectively) and in the overhead of the calls. Here, divide and conquer does not improve the complexity, but the division version has an interesting property: its two halves are independent, so they could be computed in parallel. You will see this idea again in the chapter on parallel algorithms.
All the examples of this chapter are implemented, with tests, in the course repository.
- Missing or wrong base case. The recursion never ends, or ends with a stack overflow.
- Subproblems that do not get smaller. Every call must reduce the size, or it will not reach a base case.
- Using divide and conquer with repeated subproblems. The naive Fibonacci solves the same subproblems again and again; use dynamic programming.
- Recursing where a loop is enough. Reductions () are usually better written iteratively.
🧠 Checkpoint: Counting the calls
Question: How many calls does sumByDivision make for a vector of 8 elements? And for elements?
Answer: 15 for 8 elements: the tree of calls has 8 leaves (one per element) and 7 internal nodes. In general, a tree that splits until single elements has leaves and internal nodes: calls, so the cost is still .
Summary
- Divide and conquer divides a problem into smaller subproblems of the same kind, solves them (recursively, or directly in the base case) and combines their solutions.
- It requires a recursive scheme, an efficient method for the base cases and a combination method.
- In division schemes the size is divided by a constant (); in subtraction schemes a constant is subtracted (). With a single subproblem (), the process is called reduction.
- The number of subproblems should be small, and the subproblems independent. Subtraction with several subproblems leads to exponential algorithms.
- Recursion consumes stack memory proportional to its depth; reduction schemes are often better written as loops.
Practice
- 🎁 Santa's boxes. With 1,000,000 boxes and the same scales, how many weighings are needed? And if the scales can compare three groups at once (two on the scales and one aside), how many?
- 💻 Run the three sums. Run the three versions of the sum of a vector from the course repository for increasing sizes. For which size does the subtraction version fail with a
StackOverflowErroron your computer? Does it change if you increase the stack size with-Xss? - ✍️ Maximum by division. Write a divide and conquer method that returns the maximum element of a vector by dividing it into two halves. Identify the divide, conquer and combine steps.
- 🔍 Recognize the scheme. For binary search, the factorial, Quicksort and Mergesort, indicate whether they use division or subtraction, how many subproblems they generate, and in which step (divide or combine) most of the work is done.
Errors, suggestions and public questions open a form on GitHub, visible to everyone.