Skip to main content

Divide and Conquer: Classic Problems

15 min readRead first: Analyzing Divide and Conquer · Quicksort

This lesson presents some of the most famous divide and conquer algorithms. Two of them, Mergesort and Quicksort, we already know from the sorting chapter; now we can analyze them with the formulas of this chapter. The others (the Towers of Hanoi, the multiplication of large integers, the tennis tournament and the Tromino puzzle) show how the paradigm solves problems that would be hard to approach in any other way.

What you will learn in this lesson
  • How Mergesort and Quicksort fit the division and subtraction schemes.
  • The recursive solution of the Towers of Hanoi, and why it cannot be faster than exponential.
  • How Karatsuba's algorithm multiplies large integers faster than the classic method by saving one multiplication.
  • Two constructive problems solved by divide and conquer: scheduling a tennis tournament and tiling a board with trominoes.

Mergesort​

Mergesort sorts a vector by dividing it into two halves, sorting each half recursively and merging the two sorted halves:

void mergesort(int left, int right, int[] elements) {
if (right > left) {
int center = (right + left) / 2; // index of the middle element
mergesort(left, center, elements); // sort the left half
mergesort(center + 1, right, elements); // sort the right half
combine(left, center, center + 1, right, elements); // merge both halves
}
}

To combine two sorted halves, copy them into two auxiliary arrays, then repeatedly take the smaller of the first remaining elements of both and put it back into the original array; when one of them runs out, copy the rest of the other one:

void combine(int x1, int x2, int y1, int y2, int[] elements) {
int sizeX = x2 - x1 + 1, sizeY = y2 - y1 + 1;
int[] x = new int[sizeX], y = new int[sizeY];
for (int i = 0; i < sizeX; i++) x[i] = elements[x1 + i]; // copy the left half
for (int i = 0; i < sizeY; i++) y[i] = elements[y1 + i]; // copy the right half

int i = 0, j = 0, k = x1;
while (i < sizeX && j < sizeY) // take the smaller each time
elements[k++] = (x[i] <= y[j]) ? x[i++] : y[j++];
while (i < sizeX) elements[k++] = x[i++]; // copy the rest
while (j < sizeY) elements[k++] = y[j++];
}

With 4 5 6 1 3 2 7 8:

Mergesort on 4 5 6 1 3 2 7 8: divide into halves, then merge sorted halves45613278456132784561327845613278451623781456237812345678dividebasemerge
Mergesort on 4 5 6 1 3 2 7 8: the vector is halved until the parts have one element, and the sorted parts are merged back level by level.

Analysis. Divide and conquer by division: a=2a = 2 subproblems, b=2b = 2 (each of size n/2n/2), k=1k = 1 (merging costs O(n)O(n)). Since a=bka = b^k (2=212 = 2^1): O(nklog⁡n)=O(nlog⁡n)O(n^k \log n) = O(n \log n), in all cases, because the division is always into halves, whatever the data.

Taking x[i] when x[i] <= y[j] (that is, preferring the left half in case of a tie) makes Mergesort stable. Its weakness is the extra memory for the auxiliary arrays: O(n)O(n).

ProofMergesort is correct and costs n log n

Quicksort, Revisited​

Quicksort chooses a pivot, partitions the vector in O(n)O(n) and sorts both parts recursively. The two extreme cases fit our two schemes:

  • Balanced partitions (the pivot is the median): division scheme with a=2a = 2, b=2b = 2, k=1k = 1. Since a=bka = b^k: O(nlog⁡n)O(n \log n).
  • Completely unbalanced partitions (the pivot is the smallest or largest element): one part is empty, so there is effectively one subproblem of size n−1n - 1: subtraction scheme with a=1a = 1, b=1b = 1, k=1k = 1. Since a=1a = 1: O(nk+1)=O(n2)O(n^{k+1}) = O(n^2).

The average case lies between both and, as we saw in the sorting chapter, is O(nlog⁡n)O(n \log n). Unlike Mergesort, all the work of Quicksort is done when dividing (partitioning); combining requires nothing.


The Towers of Hanoi​

There are three vertical rods and nn discs of different sizes, initially stacked on the first rod (the source) from largest at the bottom to smallest at the top. The goal is to move the whole stack to the last rod (the target), using the middle rod as an auxiliary (work) rod, with two rules:

  • only one disc can be moved at a time;
  • a disc can never be placed on top of a smaller one.

The puzzle was invented by the French mathematician Édouard Lucas in 1883, together with a legend: in a temple, monks are moving a tower of 64 golden discs, and when they finish, the world will end.

The recursive strategy​

The problem seems complicated, but divide and conquer makes it simple. To move nn discs from the source to the target:

  1. Move the top n−1n - 1 discs from the source to the work rod (using the target as auxiliary).
  2. Move the largest disc, now alone, from the source to the target.
  3. Move the n−1n - 1 discs from the work rod to the target (using the source as auxiliary).

Steps 1 and 3 are the same problem with one disc fewer, so they are solved recursively. The base case is a single disc, which is moved directly.

Towers of Hanoi with three discs: the three steps of the recursive strategystartABC1. move n − 1 discs to BABC2. move the largest disc to CABC3. move n − 1 discs onto itABCsteps 1 and 3 are the same problem with one disc fewer: M(n) = 2M(n − 1) + 1 = 2ⁿ − 1 moves
The recursive strategy for three discs. Steps 1 and 3 move a tower of n − 1 discs, the same problem with one disc fewer, and step 2 moves only the largest disc.
/** Moves nDiscs from the source rod to the target rod, with the aid of the work rod */
void move(int nDiscs, char source, char work, char target) {
if (nDiscs == 1) {
moveDisc(source, target); // a single disc: move it directly
} else {
move(nDiscs - 1, source, target, work); // 1. n-1 discs to the work rod
moveDisc(source, target); // 2. the largest disc to the target
move(nDiscs - 1, work, source, target); // 3. n-1 discs on top of it
}
}

With 3 discs on rod A (source), B (work) and C (target), the call move(3, 'A', 'B', 'C') produces 7 moves:

Move1234567
From → toA → CA → BC → BA → CB → AB → CA → C

Moves 1 to 3 transfer the two smallest discs to B; move 4 carries the largest disc to C; moves 5 to 7 transfer the two small discs on top of it.

Analysis​

Divide and conquer by subtraction: a=2a = 2 (two recursive calls), b=1b = 1 (each one with n−1n - 1 discs), k=0k = 0 (moving one disc is constant). Since a>1a \gt 1: O(an/b)=O(2n)O(a^{n/b}) = O(2^n). More precisely, the number of moves M(n)M(n) satisfies M(n)=2M(n−1)+1M(n) = 2M(n-1) + 1 with M(1)=1M(1) = 1, so M(n)=2n−1M(n) = 2^n - 1.

The complexity is not polynomial, but here this is not a flaw of the algorithm: it can be proved that no solution can use fewer than 2n−12^n - 1 moves (the largest disc must move at least once, and before it does, all the others must be out of the way, twice). The problem itself is exponential. With 64 discs, 264−1≈1.8×10192^{64} - 1 \approx 1.8 \times 10^{19} moves: at one move per second, about 585,000 million years. The world is safe.

🧠 Checkpoint: How long does Hanoi take?

Question: How many moves are needed with 10 discs? And with 30 discs, at one move per second?

Answer: With 10 discs, 210−1=2^{10} - 1 = 1,023 moves. With 30 discs, 230−1=1,073,741,8232^{30} - 1 = 1{,}073{,}741{,}823 seconds: about 34 years. Every extra disc doubles the time.


Multiplication of Large Integers​

Computers multiply numbers of fixed size (such as long) in a single instruction. But cryptography, computer algebra or the calculation of the digits of π\pi need to multiply integers with thousands or millions of digits, which must be stored as arrays of digits. How fast can we multiply two numbers of nn digits?

The classic algorithm​

The method we learnt at school multiplies each digit of one number by each digit of the other, and adds the shifted partial products:

981
× 1234
------
3924
2943
1962
981
-------
1210554

It performs n2n^2 one-digit multiplications: O(n2)O(n^2).

A first divide and conquer attempt​

Assume, to simplify, that both numbers have nn digits, with nn a power of 2. Split each number into two halves of n/2n/2 digits:

U=w⋅10n/2+xV=y⋅10n/2+zU = w \cdot 10^{n/2} + x \qquad\qquad V = y \cdot 10^{n/2} + z

Then:

U⋅V=wy⋅10n+(wz+xy)⋅10n/2+xzU \cdot V = wy \cdot 10^n + (wz + xy) \cdot 10^{n/2} + xz

This requires 4 multiplications of numbers of n/2n/2 digits (wywy, wzwz, xyxy and xzxz), which are computed recursively, plus some additions and shifts (multiplying by a power of 10 is just a shift), which are O(n)O(n). The base case is the multiplication of two one-digit numbers.

Analysis: a=4a = 4, b=2b = 2, k=1k = 1. Since a>bka \gt b^k (4>24 \gt 2): O(nlog⁡24)=O(n2)O(n^{\log_2 4}) = O(n^2). No improvement at all over the classic algorithm!

Karatsuba's algorithm​

In 1960, Anatoly Karatsuba (then a student) discovered how to save one multiplication. The key observation is:

wz+xy=(w+x)(y+z)−wy−xzwz + xy = (w + x)(y + z) - wy - xz

Since wywy and xzxz are needed anyway, the middle term costs only one extra multiplication, (w+x)(y+z)(w + x)(y + z), instead of two:

U⋅V=wy⋅10n+[(w+x)(y+z)−wy−xz]⋅10n/2+xzU \cdot V = wy \cdot 10^n + \big[(w + x)(y + z) - wy - xz\big] \cdot 10^{n/2} + xz
LargeInteger multiply(LargeInteger u, LargeInteger v) { // n digits each
if (n == 1) return u * v; // one-digit product
LargeInteger w = firstHalf(u), x = secondHalf(u);
LargeInteger y = firstHalf(v), z = secondHalf(v);
LargeInteger p = multiply(w, y); // w·y
LargeInteger q = multiply(x, z); // x·z
LargeInteger r = multiply(w.add(x), y.add(z)); // (w+x)·(y+z)
return p.shift(n).add(r.subtract(p).subtract(q).shift(n / 2)).add(q);
}
Multiplying two numbers split into halves: four products of half size, or three with KaratsubaU =wxV =yzn/2 digits each halfdirect split: 4 productsw·yw·zx·yx·zT(n) = 4T(n/2) + O(n) → O(n²): no gainKaratsuba: 3 productsw·yx·z(w+x)·(y+z)wz + xy = (w+x)(y+z) − wy − xz → T(n) = 3T(n/2) + O(n) = O(n^1.585)
Splitting both numbers into halves. The direct split needs four products of half size and gains nothing; Karatsuba's identity obtains the middle term with a single extra product, three in total.

Analysis: a=3a = 3, b=2b = 2, k=1k = 1. Since a>bka \gt b^k (3>23 \gt 2): O(nlog⁡23)≈O(n1.585)O(n^{\log_2 3}) \approx O(n^{1.585}). Saving a single multiplication in each call changes the exponent, which makes a huge difference for large numbers: for numbers of a million digits, n2=1012n^2 = 10^{12} while n1.585≈3×109n^{1.585} \approx 3 \times 10^9. We implemented this algorithm on binary numbers and checked it against Java's BigInteger on 200 random pairs of 2,000-bit numbers.

ProofKaratsuba's identity
🧠 Checkpoint: Karatsuba versus the classic method

Question: Multiplying two numbers of 1,024 digits, and recursing down to single digits, how many single-digit products does Karatsuba's algorithm compute? And the classic method?

Answer: Karatsuba halves the size 10 times (1024=2101024 = 2^{10}) and makes 3 products at each level: 310=3^{10} = 59,049 single-digit products. The classic method makes 10242=1024^2 = 1,048,576, about 18 times more.

What does Java use?​

Java's BigInteger combines several algorithms depending on the size of the operands: the classic O(n2)O(n^2) method for small numbers (where its low overhead wins), Karatsuba (O(n1.585)O(n^{1.585})) for larger numbers and Toom-Cook (O(n1.465)O(n^{1.465}), a generalization that splits into three parts) for the largest ones. Even faster algorithms, based on the fast Fourier transform, exist for gigantic numbers.


The Tennis Tournament​

We must organize a tennis tournament with nn players. Each player must play exactly once against each of the n−1n - 1 other players, and one match per day. The goal is to build the calendar of the tournament in n−1n - 1 days (when nn is even, everyone plays every day; when nn is odd, each player has one day off).

To simplify, consider first n=2kn = 2^k. The solution can be represented as a table of nn rows and n−1n - 1 columns, where the element (i,j)(i, j) is the player that faces player ii on day jj.

The strategy​

  • Base case (n=2n = 2): a single match on day 1.
  • Recursive case (n=2kn = 2^k, k>1k \gt 1): split the players into two halves, 1…n/21 \dots n/2 and n/2+1…nn/2 + 1 \dots n, and recursively build the calendar of each half, which covers the first n/2−1n/2 - 1 days. It remains to schedule the matches between both halves on the remaining n/2n/2 days:
    • the first player of the first half plays, on successive days, against the players of the second half in increasing order;
    • each following player of the first half uses the same sequence with a cyclic shift of one position;
    • the players of the second half are filled in symmetrically (if ii plays jj on a day, then jj plays ii on that day).
void schedule(int[][] table, int lower, int upper) {
if (upper - lower == 1) { // base case: two players
table[lower][1] = upper;
table[upper][1] = lower;
} else {
int center = (lower + upper) / 2;
schedule(table, lower, center); // calendar of the first half
schedule(table, center + 1, upper); // calendar of the second half
completeCrossMatches(table, lower, center, upper); // O(n²): the remaining n/2 days
}
}

For n=8n = 8, the resulting calendar (each row lists the opponents of a player, day by day) is:

PlayerDay 1Day 2Day 3Day 4Day 5Day 6Day 7
12345678
21436785
34127856
43218567
56781432
65872143
78563214
87654321

Days 1 to 3 contain the two calendars of 4 players (1-4 and 5-8), built recursively; days 4 to 7 contain the cross matches, with the cyclic shifts clearly visible. We checked the table: every player faces every other player exactly once, and the matches of each day are consistent.

Analysis. Divide and conquer by division: a=2a = 2, b=2b = 2, and completing the cross matches fills n2×n2\frac{n}{2} \times \frac{n}{2} cells for each half: k=2k = 2. Since a<bka \lt b^k (2<42 \lt 4): O(nk)=O(n2)O(n^k) = O(n^2). This is optimal, since the table itself has n(n−1)n(n-1) cells to fill.

Other values of nn. If nn is odd, add a fictitious player: the problem becomes one with an even number of players, and the day on which a player "plays" against the fictitious one is his day off. If nn is even but not a power of 2, the problem can be solved by combining the solutions for n/2n/2 players (adding a fictitious player when n/2n/2 is odd) with a slightly different completion step.


The Tromino Puzzle​

A tromino is an L-shaped figure formed by three 1×11 \times 1 squares. We have a board of n×nn \times n cells, with nn a power of 2, in which one cell is missing (or blocked). The goal is to cover all the other cells with trominoes, without overlaps. Is it always possible, wherever the missing cell is? Divide and conquer answers yes, and gives the construction at the same time:

  • Base case (n=2n = 2): a 2×22 \times 2 board with one missing cell is exactly one tromino.
  • Recursive case: divide the board into four quadrants of n2×n2\frac{n}{2} \times \frac{n}{2}. The missing cell is in one of them. Place one tromino at the center of the board, covering the corner cell of each of the other three quadrants that touches the center. Now each of the four quadrants has exactly one cell that is missing or covered, so each one is a smaller instance of the same problem, and can be tiled recursively.
An 8 by 8 board with one missing cell tiled with 21 trominoes by divide and conquer✕red: the missing cellorange: the first tromino, placed atthe center so that it covers onecell of each quadrant without amissing cellnow each quadrant is a 4 × 4 boardwith exactly one covered cell:the same problem, half the size21 trominoes = (8² − 1) / 3
An 8 × 8 board with one missing cell (red), tiled by divide and conquer. The first tromino (orange) is placed at the center so that each quadrant has exactly one missing or covered cell; each quadrant is then tiled in the same way.

The number of cells to cover is n2−1n^2 - 1, which is always divisible by 3 when nn is a power of 2, and the algorithm uses exactly n2−13\frac{n^2 - 1}{3} trominoes.

Analysis. With nn as the side of the board: a=4a = 4 subproblems, b=2b = 2, and placing the central tromino is constant, k=0k = 0. Since a>bka \gt b^k: O(nlog⁡24)=O(n2)O(n^{\log_2 4}) = O(n^2), proportional to the number of cells, which is optimal. You can try the puzzle interactively at the Tromino puzzle page by Norton Starr.

The Tromino puzzle is also a beautiful example of a proof by induction: the recursive algorithm is, at the same time, a proof that the tiling always exists.

Common mistakes
  • Expecting four half-size products to beat the classic multiplication. With a=4a = 4, b=2b = 2, k=1k = 1 it is still O(n2)O(n^2); Karatsuba needs only three.
  • Forgetting the auxiliary array of Mergesort. It is not in place: it needs O(n)O(n) extra memory.
  • Looking for a polynomial algorithm for the Towers of Hanoi. 2n−12^n - 1 moves are necessary: the problem itself is exponential.

Summary​

ProblemSchemeaabbkkComplexity
MergesortDivision221O(nlog⁡n)O(n \log n)
Quicksort, best caseDivision221O(nlog⁡n)O(n \log n)
Quicksort, worst caseSubtraction111O(n2)O(n^2)
Towers of HanoiSubtraction210O(2n)O(2^n)
Large integers, 4 productsDivision421O(n2)O(n^2)
KaratsubaDivision321O(n1.585)O(n^{1.585})
Tennis tournamentDivision222O(n2)O(n^2)
Tromino (nn = side)Division420O(n2)O(n^2)

Practice​

  • ✍️ Trace Mergesort. Sort 5 6 1 3 9 8 7 4 2 with Mergesort, drawing the tree of divisions and the result of each merge.
  • 🗼 Hanoi. Write the sequence of moves for 4 discs. Then write a program that prints the moves and measures the time for n=20,21,22,…n = 20, 21, 22, \dots Does the time double with each additional disc?
  • ✖️ Karatsuba by hand. Multiply 1234×56781234 \times 5678 with Karatsuba's method, writing the three products of the first level.
  • 🎾 The calendar. Build the calendar for n=4n = 4 players by hand with the strategy of this lesson. Then implement completeCrossMatches and check your table for n=8n = 8 against the one above.
  • 🧩 Trominoes. Tile by hand an 8×88 \times 8 board with the missing cell at row 2, column 6. How many trominoes do you need?
Saved only in your browser
Was this lesson helpful?
Questions, or something wrong?

Errors, suggestions and public questions open a form on GitHub, visible to everyone.