---
title: "Divide and Conquer"
book: "University Computer Science — Year 1"
subject: computer-science
language: en
chapter: 21
exercises: 12
source: https://one-course.com/books/computer-science/3/en/chapter/21-divide-and-conquer
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 21 — Divide and Conquer

Multiplying two numbers of 1000 digits by the method taught at school takes a million products of digits, one for each digit of the first number and each digit of the second. For centuries nobody expected to do better: every digit of one number must meet every digit of the other, it seems. It does not have to. Cutting each number in two halves and combining three products of halves, instead of four, gives a method whose cost grows like $n^{1.585}$, and that is how long numbers are multiplied in practice. The idea behind it, cutting a problem into smaller ones of the same kind, has already given [merge sort](https://one-course.com/books/computer-science/3/en/chapter/19-sorting#def-b1-sorting-merge-sort); this chapter turns it into a method and applies it to five problems.

**You already know.**

The master theorem ([Theorem 13.12](https://one-course.com/books/computer-science/3/en/chapter/13-asymptotic-analysis-and-recurrences#thm-b1-asymptotic-analysis-master)) solves $T(n) = aT(n/b) + n^k$: $T(n) =
\Theta(n^k)$ if $a < b^k$, $\Theta(n^k \log n)$ if $a = b^k$, and $\Theta(n^{\log_b a})$ if $a > b^k$; a cost $\Theta(n^k)$ in place of $n^k$ gives the same orders. [Merge sort](https://one-course.com/books/computer-science/3/en/chapter/19-sorting#def-b1-sorting-merge-sort) ([Definition 19.7](https://one-course.com/books/computer-science/3/en/chapter/19-sorting#def-b1-sorting-merge-sort)) satisfies $T(n) = 2T(n/2) + \Theta(n)$, hence $\Theta(n
\log n)$. An inversion of a sequence is a pair of positions $i < j$ whose keys are out of order ([Definition 19.3](https://one-course.com/books/computer-science/3/en/chapter/19-sorting#def-b1-sorting-inversion)).

## 21.1 The method and its recurrences

**Definition 21.1 (Divide and conquer).**

A *divide and conquer* algorithm solves an instance of a problem in three steps: *divide* it into smaller instances of the same problem, *solve* each of them by a recursive call (or directly when it is small enough), and *combine* their solutions into a solution of the instance.

The method was met informally in the second book, on searching a sorted list and sorting by merging. Its analysis is always the same: if an instance of size $n$ is cut into $a$ instances of size $n/b$, and dividing plus combining cost $f(n)$, the cost is $T(n) = aT(n/b) + f(n)$, and the master theorem gives its order. The work lies in finding a cheap combine step, or in making $a$ small.

Counting inversions shows the three steps at their simplest. The inversions of a list are those inside its left half, those inside its right half, and those with one key on each side. The recursive calls count the first two kinds; the third kind is counted while merging the two sorted halves: when a key is taken from the right half, every key still waiting in the left half is larger and comes before it.

```python
def sort_count(a):
    """(sorted copy of a, number of pairs i < j with a[i] > a[j])."""
    if len(a) <= 1:
        return list(a), 0
    mid = len(a) // 2
    left, x = sort_count(a[:mid])  # divide, and solve each half
    right, y = sort_count(a[mid:])
    merged, z, i = [], 0, 0  # combine: merge, counting the pairs split by mid
    for r in right:
        while i < len(left) and left[i] <= r:
            merged.append(left[i])
            i += 1
        z += len(left) - i  # r is smaller than every key left in `left`
        merged.append(r)
    merged += left[i:]
    return merged, x + y + z
```

***Listing 21.1.** Counting inversions while sorting code/bachelor-1/21-divide-and-conquer/listings/inversions.py*

```
([1, 1, 2, 3, 4, 5, 6, 9], 8)
```

***Output 21.1.** The sorted list and its 8 inversions. Some lines are left out.*

The combine step costs $\Theta(n)$, so $T(n) = 2T(n/2) + \Theta(n) = \Theta(n \log n)$, against $\Theta(n^2)$ for testing every pair. Sorting was not asked for, but it makes the combine step cheap: a [divide and conquer](#def-b1-divide-and-conquer-dc) algorithm often returns more than the question, to make the next combination easy.

## 21.2 Karatsuba’s multiplication

A number of $n$ digits is a list of digits, least significant first. The school method adds the product of digit $i$ of $a$ and digit $j$ of $b$ into cell $i + j$ of the result, then propagates the carries.

```python
def normalise(r):
    """Propagate carries in place: every cell back to 0..9 (cells may be negative)."""
    carry = 0
    for i in range(len(r)):
        carry, r[i] = divmod(r[i] + carry, 10)
    assert carry == 0, "the result does not fit"
    return r


def school(a, b):
    """The school method: every digit of a times every digit of b."""
    global products
    r = [0] * (len(a) + len(b))
    for i, x in enumerate(a):
        for j, y in enumerate(b):
            r[i + j] += x * y
        products += len(b)
    return normalise(r)
```

***Listing 21.2.** Carries, and the school method with its counter of digit products code/bachelor-1/21-divide-and-conquer/listings/digits.py*

Cut each number in two halves of $m = n/2$ digits: $a = a_1 10^m + a_0$ and $b = b_1 10^m + b_0$. Then

$$
ab = a_1 b_1 10^{2m} + (a_1 b_0 + a_0 b_1) 10^m + a_0 b_0,
$$

four products of halves, and $T(n) = 4T(n/2) + \Theta(n)$ is $\Theta(n^2)$ again: cutting alone gains nothing. But the middle term is a combination of the two others and of a single new product:

$$
a_1 b_0 + a_0 b_1 = a_1 b_1 + a_0 b_0 - (a_1 - a_0)(b_1 - b_0).
$$

**Method 21.2 (Karatsuba’s algorithm).**

To multiply two numbers of $n = 2m$ digits, compute recursively $z_2 = a_1 b_1$, $z_0 = a_0 b_0$ and $z_1 = |a_1 -
a_0| \cdot |b_1 - b_0|$, with $s$ the sign of $(a_1 - a_0)(b_1 - b_0)$, and return $z_2 10^{2m} + (z_2 + z_0 - s z_1)
10^m + z_0$. Numbers of one digit are multiplied directly.

The differences $|a_1 - a_0|$ and $|b_1 - b_0|$ are less than $10^m$: they have $m$ digits, like the halves, so that the three recursive calls are on numbers of $m$ digits exactly.

```python
def difference(x, y):
    """(|x - y|, sign of x - y) for digit lists x, y of one length."""
    sign = 1
    for u, v in zip(reversed(x), reversed(y)):  # compare from the top digit
        if u != v:
            sign = 1 if u > v else -1
            break
    if sign < 0:
        x, y = y, x
    return normalise([u - v for u, v in zip(x, y)]), sign


def karatsuba(a, b, cutoff=1):
    """Product of two digit lists of one length n, a power of 2; 2n digits."""
    n = len(a)
    if n <= cutoff:
        return school(a, b)
    m = n // 2
    a0, a1, b0, b1 = a[:m], a[m:], b[:m], b[m:]  # a = a1 * 10^m + a0
    z0 = karatsuba(a0, b0, cutoff)
    z2 = karatsuba(a1, b1, cutoff)
    da, sa = difference(a1, a0)
    db, sb = difference(b1, b0)
    z1 = karatsuba(da, db, cutoff)  # (a1 - a0)(b1 - b0) = sa * sb * z1
    r = [0] * (2 * n)
    for i in range(2 * m):  # a1 b0 + a0 b1 = z2 + z0 - (a1 - a0)(b1 - b0)
        r[i] += z0[i]
        r[i + m] += z0[i] + z2[i] - sa * sb * z1[i]
        r[i + 2 * m] += z2[i]
    return normalise(r)
```

***Listing 21.3.** The difference of two halves, and Karatsuba’s multiplication code/bachelor-1/21-divide-and-conquer/listings/karatsuba.py*

The combine loop adds and subtracts into cells that may go negative; `normalise` takes them back to digits with floor division, and its [assertion](https://one-course.com/books/computer-science/3/en/chapter/7-modular-programs-makefiles-and-tests#def-b1-c-modules-make-tests-assertion) checks that the result fits in $2n$ digits, as the product of two $n$-digit numbers must.

![The recursion tree of Karatsuba’s algorithm on n = 2k digits: three children per node. Level i holds 3i calls on n/2i digits, and the combine work of the level is (3/2)i (n), growing to the leaves. The same cut with four products (in red) has 4i calls at level i.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-divide-and-conquer/fig-a1c9f4e9ca68.svg)

*The [recursion tree](https://one-course.com/books/computer-science/3/en/chapter/13-asymptotic-analysis-and-recurrences#def-b1-asymptotic-analysis-recurrence) of [Karatsuba’s algorithm](#met-b1-divide-and-conquer-karatsuba) on $n = 2^k$ digits: three children per node. Level $i$ holds $3^i$ calls on $n/2^i$ digits, and the combine work of the level is $(3/2)^i \Theta(n)$, growing to the leaves. The same cut with four products (in red) has $4^i$ calls at level $i$.*

The recurrence is now $T(n) = 3T(n/2) + \Theta(n)$, and $3 > 2^1$: the master theorem gives $\Theta(n^{\log_2 3})$, with $\log_2 3 \approx 1.585$. The program counts the products exactly.

```
$ python karatsuba.py
school   : 1234 x 5678 = 7006652, 16 digit products
karatsuba: 1234 x 5678 = 7006652, 9 digit products
    n   school karatsuba     3^k
    1        1         1       1
    2        4         3       3
    4       16         9       9
    8       64        27      27
   16      256        81      81
   32     1024       243     243
   64     4096       729     729
  128    16384      2187    2187
  256    65536      6561    6561
  512   262144     19683   19683
 1024  1048576     59049   59049
```

***Output 21.2.** Digit products of the two methods, on a small example and on $n$ nines times $n$ nines.*

Fewer products do not mean less time: each call also pays for two differences, a combine loop and its carries, and a call costs much more than a product of digits. Below some size, the school method wins. A *cutoff* makes Karatsuba’s method fall back on the school method for numbers of at most that many digits.

```
$ python karatsuba_timing.py
    n    school   cutoff 1   cutoff 8  cutoff 32
   16         8         98         12          8
   32        29        314         47         35
   64       113        918        142         99
  128       418       2893        489        339
  256      1773       9019       1534       1047
  512      9412      26366       4425       3204
 1024     39270      79194      14331       9772
 2048    167668     237497      41350      29815
```

***Output 21.3.** Microseconds per product of two random $n$-digit numbers, on the author’s laptop, for the school method and Karatsuba’s with three cutoffs.*

![Left: digit products counted in ; the slopes are 2 and _2 3. Right: the measured times of ; without a cutoff, Karatsuba’s method is still slower at 2048 digits, with a cutoff of 32 it is faster from 64 digits on.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-divide-and-conquer/fig-cdbac1d919ab.svg)

![Left: digit products counted in ; the slopes are 2 and _2 3. Right: the measured times of ; without a cutoff, Karatsuba’s method is still slower at 2048 digits, with a cutoff of 32 it is faster from 64 digits on.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-divide-and-conquer/fig-7ff333b14a19.svg)

*Left: digit products counted in [Output 21.2](#out-b1-divide-and-conquer-karatsuba); the slopes are 2 and $\log_2 3$. Right: the measured times of [Output 21.3](#out-b1-divide-and-conquer-timing); without a cutoff, Karatsuba’s method is still slower at 2048 digits, with a cutoff of 32 it is faster from 64 digits on.*

**History — Three products instead of four.**

The method was published by Karatsuba and Ofman in 1962. In 1969, Strassen applied the same idea to matrices: two $2
\times 2$ block matrices can be multiplied with 7 block products instead of 8, which gives $\Theta(n^{\log_2 7})$, about $n^{2.81}$ operations, for $n \times n$ matrices.

**Facts as of 2026.**

CPython multiplies its integers by the school method unless both have more than 70 internal digits, of 30 bits each, about 630 decimal digits; above that it uses Karatsuba’s method. This is read in its source code, and such thresholds change between versions.

## 21.3 The closest pair of points

**Definition 21.3 (Closest-pair problem).**

The *closest-pair problem* asks, for $n \geq 2$ distinct points of the plane, for the smallest distance between two of them.

Comparing every pair takes $n(n - 1)/2$ distances. [Divide and conquer](#def-b1-divide-and-conquer-dc) sorts the points by $x$, cuts them by a vertical line through the median $x$, and solves both halves: $\delta$ is the smaller of the two answers. A closer pair can only have one point on each side, both within $\delta$ of the line: in the *strip* of width $2\delta$ around it.

**Proposition 21.4 (Seven neighbours suffice).**

Sort the points of the strip by $y$. If two of them, $p$ before $q$, are less than $\delta$ apart, then $q$ is one of the seven points that follow $p$.

**Proof.** All the points that follow $p$ and are within $\delta$ of it lie in the rectangle of width $2\delta$ and height $\delta$ whose bottom edge passes through $p$, centred on the line. Cut this rectangle into eight squares of side $\delta/2$, four on each side of the line. Two points in one square are at most $\delta/\sqrt{2} < \delta$ apart, and on one side of the line, which contradicts the definition of $\delta$: each square holds at most one point. With $p$ itself, the rectangle holds at most eight points, so at most seven points come after $p$ before the first one with $y \geq p_y +
\delta$. ∎

![The strip argument. The points that follow p in the y order and are within of it lie in the shaded 2 × rectangle; each of its eight squares holds at most one point. Points on one side are at least apart; the point just right of the line is the one that can beat .](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-divide-and-conquer/fig-ccc2513ee074.svg)

*The strip argument. The points that follow $p$ in the $y$ order and are within $\delta$ of it lie in the shaded $2\delta \times \delta$ rectangle; each of its eight squares holds at most one point. Points on one side are at least $\delta$ apart; the point just right of the line is the one that can beat $\delta$.*

```python
def solve(px):
    """(smallest distance, the points of px sorted by y); px is sorted by x."""
    n = len(px)
    if n <= 3:
        best = min((d(p, q) for i, p in enumerate(px) for q in px[i + 1:]), default=inf)
        return best, sorted(px, key=lambda p: p[1])
    mid = n // 2
    x_mid = px[mid][0]
    dl, left = solve(px[:mid])
    dr, right = solve(px[mid:])
    delta = min(dl, dr)
    py = merge_by_y(left, right)
    strip = [p for p in py if abs(p[0] - x_mid) < delta]  # still sorted by y
    for i, p in enumerate(strip):
        for q in strip[i + 1:i + 8]:  # at most 7 points can follow within delta
            if q[1] - p[1] >= delta:
                break
            delta = min(delta, d(p, q))
    return delta, py
```

***Listing 21.4.** The closest pair, returning the points sorted by $y$ for the caller’s strip code/bachelor-1/21-divide-and-conquer/listings/closest_pair.py*

Each call returns its points sorted by $y$, merged from the two halves, so that the strip is sorted without sorting: the combine step costs $\Theta(n)$ and the whole $\Theta(n \log n)$. On the town’s 30 places and on random points:

```
$ python closest_pair.py
town: 30 places; closest: Cinema and Football Ground, 405 m
    n divide and conquer brute force
  250                260       31125
  500                572      124750
 1000               1127      499500
 2000               2308     1999000
```

***Output 21.4.** The closest pair of the town’s places, and distances computed on random points, against [brute force](https://one-course.com/books/computer-science/3/en/chapter/20-exhaustive-search-and-backtracking#def-b1-backtracking-exhaustive).*

On random points the strip is thin and holds few points: barely more than one distance per point.

## 21.4 Selection in linear time

**Definition 21.5 (Selection problem, quickselect, median of medians).**

The *selection problem* asks for the key of rank $k$ of $n$ keys, the one that would be at position $k$ if they were sorted; the median is the key of rank $\lfloor (n - 1)/2 \rfloor$. *Quickselect* partitions the keys around a pivot, as [quicksort](https://one-course.com/books/computer-science/3/en/chapter/19-sorting#def-b1-sorting-quicksort) does, and goes on in the one part that holds rank $k$. The *median of medians* chooses as pivot the median of the medians of groups of five keys, found by a recursive call.

Sorting answers in $\Theta(n \log n)$; selection needs less. [Quickselect](#def-b1-divide-and-conquer-selection) makes one recursive call instead of two, so with pivots that halve the keys its cost is $n + n/2 + n/4 + \dots \leq 2n$ partition steps. With bad pivots it is quadratic, like [quicksort](https://one-course.com/books/computer-science/3/en/chapter/19-sorting#def-b1-sorting-quicksort).

```python
def split(a, pivot):
    """The keys of a below, equal to and above pivot."""
    low, high = [x for x in a if less(x, pivot)], [x for x in a if less(pivot, x)]
    return low, len(a) - len(low) - len(high), high


def quickselect(a, k, rng=None):
    """The key of rank k (0 = smallest); pivot: the last key, or a random one."""
    while True:
        pivot = a[-1] if rng is None else rng.choice(a)
        low, equal, high = split(a, pivot)
        if k < len(low):
            a = low
        elif k < len(low) + equal:
            return pivot
        else:
            a, k = high, k - len(low) - equal
def mom_select(a, k):
    """The key of rank k, with the median of the medians of groups of five as pivot."""
    if len(a) <= 5:
        return sort5(a)[k]
    groups = [a[i:i + 5] for i in range(0, len(a), 5)]
    medians = [sort5(g)[(len(g) - 1) // 2] for g in groups]
    pivot = mom_select(medians, (len(medians) - 1) // 2)
    low, equal, high = split(a, pivot)
    if k < len(low):
        return mom_select(low, k)
    if k < len(low) + equal:
        return pivot
    return mom_select(high, k - len(low) - equal)
```

***Listing 21.5.** Partition, [quickselect](#def-b1-divide-and-conquer-selection), and the [median of medians](#def-b1-divide-and-conquer-selection) code/bachelor-1/21-divide-and-conquer/listings/selection.py*

```
$ python selection.py
     n quick, sorted quick, random quick, rnd pivot mom, sorted mom, random
  1000        750500          6804             6482        8359       10754
  2000       3001000         10884             6696       17183       21081
  4000      12002000         18484            21652       35095       43256
  8000      48004000         40984            42240       71099       88584
```

***Output 21.5.** Comparisons to find the key of rank $n/2$ (the upper median) of $n$ keys, sorted or shuffled.*

On a sorted list, the last key as pivot is the largest, and [quickselect](#def-b1-divide-and-conquer-selection) removes one key per round: rounds on $n$, $n - 1$, …, $n/2$ keys, about $3n^2/8$ keys partitioned in all, two comparisons per key: about $3n^2/4$, the 750 500 of the table for $n = 1000$. A random pivot gives a linear cost on average. The [median of medians](#def-b1-divide-and-conquer-selection) gives it in the worst case.

![Thirty-five keys in seven columns of five, columns ordered by their median; the circled key, the median of the medians, is the pivot. The shaded block below and left holds keys no larger than the pivot, the one above and right keys no smaller: each about 3/10 of all keys.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-divide-and-conquer/fig-2d6c0e3883ec.svg)

*Thirty-five keys in seven columns of five, columns ordered by their median; the circled key, the median of the medians, is the pivot. The shaded block below and left holds keys no larger than the pivot, the one above and right keys no smaller: each about $3/10$ of all keys.*

**Theorem 21.6 (Selection in linear time).**

The [median of medians](#def-b1-divide-and-conquer-selection) finds the key of rank $k$ of $n$ keys in $O(n)$ comparisons.

**Proof.** Of the $g = \lceil n/5 \rceil$ medians, at least $\lceil g/2 \rceil$ are at most the pivot, and each of their groups, except perhaps the pivot’s own and a last incomplete one, holds three keys at most the pivot. So at least $3(\lceil
g/2 \rceil - 2) \geq 3n/10 - 6$ keys are at most the pivot; likewise at least that many are at least the pivot. The recursive call on one side therefore receives at most $7n/10 + 6$ keys. Sorting the groups and partitioning cost at most $an$ comparisons for a constant $a$, so

$$
T(n) \leq T(\lceil n/5 \rceil) + T(7n/10 + 6) + an.
$$

Suppose $T(j) \leq cj$ for $j < n$, with $n \geq 140$ and $c = 20a$, and $T$ bounded by $cj$ on small sizes by taking $c$ larger if needed. Then $T(n) \leq c(n/5 + 1) + c(7n/10 + 6) + an = cn - c(n/10 - 7) + an$, and $n/10 - 7 \geq
n/20$ for $n \geq 140$, so $T(n) \leq cn - cn/20 + an = cn$. ∎

The proof works because $1/5 + 7/10 < 1$: the two calls together receive less than the whole. Groups of three fail this test ([Exercise 21.10](#exo-b1-divide-and-conquer-10)). The constant is large: eight to eleven comparisons per key in [Output 21.5](#out-b1-divide-and-conquer-select), against three to seven for [quickselect](#def-b1-divide-and-conquer-selection) on shuffled keys or with random pivots. A practical routine runs [quickselect](#def-b1-divide-and-conquer-selection) and can fall back on a guaranteed method when the recursion goes too deep, as [introsort](https://one-course.com/books/computer-science/3/en/chapter/19-sorting#def-b1-sorting-introsort) does for sorting. The algorithm is due to Blum, Floyd, Pratt, Rivest and Tarjan, in 1973.

## 21.5 Dichotomy on the answer, and meeting in the middle

Binary search halves a sorted [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) ([Proposition 12.6](https://one-course.com/books/computer-science/3/en/chapter/12-program-correctness#prop-b1-program-correctness-bsearch)). It halves anything ordered, including the answers to a question.

**Definition 21.7 (Monotone predicate, dichotomy on the answer).**

A predicate $P$ on the integers is *monotone* if $P(x)$ implies $P(x + 1)$: false up to some point, true after it. A *dichotomy on the answer* finds the smallest $x$ in $[lo, hi]$ with $P(x)$, knowing $P(hi)$, by binary search on $x$, with $\lceil \log_2 (hi - lo + 1) \rceil$ evaluations of $P$.

The town wants to cover its 30 places with $k$ snow-clearing zones, each a band of the same width from west to east. For a given width, a greedy pass decides whether $k$ bands suffice: start a band at the westernmost place not yet covered. A larger width never needs more bands, so the predicate is [monotone](#def-b1-divide-and-conquer-dichotomy), and the smallest width is found by dichotomy.

```python
def covers(xs, k, length):
    """Can k segments of this length cover the sorted points xs? (greedy)"""
    used, end = 0, None
    for x in xs:
        if end is None or x > end:  # x is not covered: a new segment starts at x
            used += 1
            end = x + length
    return used <= k


def smallest_length(xs, k):
    """The smallest integer length that works: covers is false below it, true above."""
    lo, hi = 0, xs[-1] - xs[0]  # covers(hi) is true: one segment suffices
    calls = 0
    while lo < hi:  # the answer is in [lo, hi]
        mid = (lo + hi) // 2
        calls += 1
        if covers(xs, k, mid):
            hi = mid
        else:
            lo = mid + 1
    return lo, calls
```

***Listing 21.6.** The greedy test and the dichotomy on the width code/bachelor-1/21-divide-and-conquer/listings/segments.py*

```
$ python segments.py
30 places, x from 33 to 5657 m
 k length (m) calls
 1       5624    12
 2       2786    12
 3       1824    12
 4       1333    12
 5        921    12
 6        772    12
 7        667    13
 8        612    13
```

***Output 21.6.** The smallest width of $k$ bands covering the town’s places, and the number of tests.*

Twelve or thirteen tests decide among 5625 widths. The method applies whenever checking an answer is easier than finding it, and the check is [monotone](#def-b1-divide-and-conquer-dichotomy).

**Definition 21.8 (Meet in the middle).**

*Meeting in the middle* splits a search over choices into two halves, lists the partial results of each half, and finds the compatible pairs by sorting or hashing, instead of trying every combination.

The subset-sum search of [Chapter 20](https://one-course.com/books/computer-science/3/en/chapter/20-exhaustive-search-and-backtracking#ch-b1-backtracking) visits up to $2^n$ subsets. Split the $n$ values into two halves: each has $2^{n/2}$ subset sums; a subset of all the values sums to the target exactly when its left part sums to $s$ and its right part to $\mathit{target} - s$. A table of how many right subsets give each sum answers that question for all $s$.

```python
def all_sums(values):
    """The sums of the 2^len(values) subsets (with repetitions)."""
    sums = [0]
    for v in values:
        sums += [s + v for s in sums]  # each subset without v, then with v
    return sums


def count(values, target):
    """(number of subsets summing to target, sums computed)."""
    half = len(values) // 2
    left, right = all_sums(values[:half]), all_sums(values[half:])
    right_count = Counter(right)  # how many right subsets give each sum
    found = sum(right_count[target - s] for s in left)
    return found, len(left) + len(right)
```

***Listing 21.7.** Subset sum by meeting in the middle code/bachelor-1/21-divide-and-conquer/listings/meet_middle.py*

```
$ python meet_middle.py
 n    lists      subsets 2^n sums computed
16        9            65536           512
24       31         16777216          8192
32      147       4294967296        131072
40      459    1099511627776       2097152
```

***Output 21.7.** Reading lists of exactly 1000 pages from the first $n$ books.*

The counts for 16 and 24 books are those found by [backtracking](https://one-course.com/books/computer-science/3/en/chapter/20-exhaustive-search-and-backtracking#def-b1-backtracking-backtracking) in [Output 20.6](https://one-course.com/books/computer-science/3/en/chapter/20-exhaustive-search-and-backtracking#out-b1-backtracking-subset-sum). The cost is $\Theta(2^{n/2})$ sums and table operations, with a table of the same size: memory is traded for time. Forty books are reached with two million sums, where the full tree has a trillion leaves.

## 21.6 Exercises

**Exercise 21.1 ★.**

List the inversions of $[3, 1, 4, 1, 5, 9, 2, 6]$ and check the count of [Output 21.1](#out-b1-divide-and-conquer-inversions). How many are counted by the top-level merge?

**Solution of Exercise 21.1.**

The 3 is larger than both 1s and the 2; the 4 than the second 1 and the 2; the 5 than the 2; the 9 than the 2 and the 6: $3 + 2 + 1 + 2 = 8$. The left half $[3, 1, 4, 1]$ has 3 inversions, the right half $[5, 9, 2, 6]$ has 3, and the top-level merge counts the 2 pairs across the middle, $(3, 2)$ and $(4, 2)$.

**Exercise 21.2 ★.**

Give the three products of halves that Karatsuba’s method computes at the top level for $1234 \times 5678$, the sign $s$, and the result.

**Solution of Exercise 21.2.**

$a_1 = 12$, $a_0 = 34$, $b_1 = 56$, $b_0 = 78$. $z_2 = 12 \times 56 = 672$, $z_0 = 34 \times 78 = 2652$, $z_1 = |12 -
34| \cdot |56 - 78| = 22 \times 22 = 484$, and $s = (-1)(-1) = 1$. The middle term is $672 + 2652 - 484 = 2840$ (indeed $12 \times 78 + 34 \times 56 = 936 + 1904$), and $672 \cdot 10^4 + 2840 \cdot 10^2 + 2652 = 7\,006\,652$.

**Exercise 21.3 ★.**

Run `quickselect` by hand on $[7, 2, 9, 4, 1, 8, 5]$ with $k = 5$ and the last key as pivot: give the pivots and the parts kept.

**Solution of Exercise 21.3.**

Pivot 5: below $[2, 4, 1]$, above $[7, 9, 8]$; rank 5 is above, at rank $5 - 4 = 1$ there. Pivot 8: below $[7]$, one key equal; rank 1 is the pivot: the answer is 8, the key of rank 5 of $1, 2, 4, 5, 7, 8, 9$.

**Exercise 21.4 ★.**

For the points $0, 3, 4, 10, 12, 20$ and $k = 2$, give the values of `covers` for every width, and the widths the dichotomy tests.

**Solution of Exercise 21.4.**

`covers` is false for the widths 0 to 9 (at width 9 the bands $[0, 9]$, $[10, 19]$ and $[20, 29]$ are needed) and true from 10 on ($[0, 10]$ and $[12, 22]$). The dichotomy on $[0, 20]$ tests 10 (true), 5, 8 and 9 (false), and returns 10 after four tests.

**Exercise 21.5 ★★.**

This version compares each point of the strip with the next one only. Explain the counterexample it finds.

```python
def closest(px):  # px sorted by x
    if len(px) <= 3:
        return min(dist(p, q) for i, p in enumerate(px) for q in px[i + 1:])
    mid = len(px) // 2
    delta = min(closest(px[:mid]), closest(px[mid:]))
    strip = [p for p in px if abs(p[0] - px[mid][0]) < delta]
    strip.sort(key=lambda p: p[1])
    for p, q in zip(strip, strip[1:]):  # only neighbours in the y order
        delta = min(delta, dist(p, q))
    return delta
```

***Listing 21.8.** A strip checked too lightly code/bachelor-1/21-divide-and-conquer/listings/exo_strip_bug.py*

```
trial 127: [(0, 0), (4, 6), (5, 8), (7, 2), (9, 7)]
returned 4.123, true 2.236
```

***Output 21.8.** Against [brute force](https://one-course.com/books/computer-science/3/en/chapter/20-exhaustive-search-and-backtracking#def-b1-backtracking-exhaustive). Some lines are left out.*

**Solution of Exercise 21.5.**

The halves give $\delta \approx 4.123$, and the strip around $x = 5$ holds $(4, 6)$, $(5, 8)$, $(7, 2)$ and $(9, 7)$. In the $y$ order they are $(7, 2)$, $(4, 6)$, $(9, 7)$, $(5, 8)$: the closest pair, $(4, 6)$ and $(5, 8)$, at $\sqrt5
\approx 2.236$, is separated by $(9, 7)$, which is far from both in $x$. Neighbours in the $y$ order are not enough: the proposition allows up to seven points between, and the loop must go on while the $y$ distance is below $\delta$.

**Exercise 21.6 ★★.**

This dichotomy computes a cube root with an absolute tolerance. Explain why it never ends for $y = 10^{15}$, and repair it.

```python
def cube_root(y, tolerance=1e-12, limit=2000):
    lo, hi = 0.0, max(1.0, y)
    steps = 0
    while hi - lo > tolerance:
        mid = (lo + hi) / 2
        if mid**3 < y:
            lo = mid
        else:
            hi = mid
        steps += 1
        if steps == limit:  # a guard, so that the demonstration stops
            print(f"y = {y:g}: stuck after {steps} steps, lo = {lo!r}, hi = {hi!r},"
                  f" mid == hi: {mid == hi}")
            return None
    return lo
```

***Listing 21.9.** A dichotomy on reals code/bachelor-1/21-divide-and-conquer/listings/exo_float_bisect.py*

```
y = 2: 1.2599210498947286 after the loop
y = 1e+06: 99.9999999999994 after the loop
y = 1e+15: stuck after 2000 steps, lo = 99999.99999999999, hi = 100000.0, mid == hi: True
```

***Output 21.9.** Three cube roots. Some lines are left out.*

**Solution of Exercise 21.6.**

Near $10^5$, two consecutive doubles differ by $2^{16 - 52} = 2^{-36} \approx 1.5 \times 10^{-11}$, more than the tolerance. When $lo$ and $hi$ are consecutive doubles, their mean rounds to one of them, the loop assigns it, and nothing changes: the output shows $mid = hi$. Repairs: stop when $mid$ equals $lo$ or $hi$; or use a relative tolerance, $hi - lo > 10^{-12} \cdot hi$; or run a fixed number of halvings (about 110 here cover the 50 bits of the initial width and the 53 bits of precision).

**Exercise 21.7 ★★.**

Compute the largest sum of a non-empty slice of a list by [divide and conquer](#def-b1-divide-and-conquer-dc), in $O(n \log n)$, and test it against a linear method that keeps the best sum ending at each position.

**Solution of Exercise 21.7.**

```python
def best(a, lo=0, hi=None):
    """The largest sum of a non-empty slice of a[lo:hi]."""
    if hi is None:
        hi = len(a)
    if hi - lo == 1:
        return a[lo]
    mid = (lo + hi) // 2
    left_end, s = a[mid - 1], 0  # best slice ending at mid - 1
    for i in range(mid - 1, lo - 1, -1):
        s += a[i]
        left_end = max(left_end, s)
    right_start, s = a[mid], 0  # best slice starting at mid
    for i in range(mid, hi):
        s += a[i]
        right_start = max(right_start, s)
    return max(best(a, lo, mid), best(a, mid, hi), left_end + right_start)
```

*Largest slice sum code/bachelor-1/21-divide-and-conquer/exercises/max_subarray.py*

A best slice lies in the left half, in the right half, or across the middle, where it is a best slice ending at $mid -
1$ followed by a best slice starting at $mid$; both are found by one scan. So $T(n) = 2T(n/2) + \Theta(n) = \Theta(n
\log n)$. The test compares with Kadane’s linear scan and with all slices on 200 random lists.

**Exercise 21.8 ★★.**

A *majority key* of a list is held by more than half of its positions. Find it, or report that there is none, by [divide and conquer](#def-b1-divide-and-conquer-dc) in $O(n \log n)$.

**Solution of Exercise 21.8.**

```python
def majority(a):
    """The majority key of a, or None."""
    if len(a) == 1:
        return a[0]
    mid = len(a) // 2
    candidates = {majority(a[:mid]), majority(a[mid:])} - {None}
    for c in candidates:  # a majority of a is a majority of one half
        if 2 * a.count(c) > len(a):
            return c
    return None
```

*Majority key code/bachelor-1/21-divide-and-conquer/exercises/majority.py*

If a key $c$ held at most half of each half, it would hold at most $\lfloor mid/2 \rfloor + \lfloor (n - mid)/2 \rfloor
\leq n/2$ positions: a majority key of the list is a majority key of one half. So it is one of the at most two candidates returned by the halves, and counting each costs $\Theta(n)$: $T(n) = 2T(n/2) + \Theta(n) = \Theta(n \log n)$.

**Exercise 21.9 ★★.**

Karatsuba’s method pads numbers of $n$ digits to the next power of 2. Show that it makes fewer than $3 n^{\log_2 3}$ digit products, and that with a cutoff $2^j$ it makes $3^{k-j} 4^j$ on $2^k$ digits.

**Solution of Exercise 21.9.**

For numbers of $d$ digits, `multiply` takes the smallest power $2^k \geq d$, so $2^k < 2d$ and $3^k = (2^k)^{\log_2
3} < (2d)^{\log_2 3} = 3 d^{\log_2 3}$. With a cutoff $2^j$, $K(2^k) = 3K(2^{k-1})$ for $k > j$ and $K(2^j) = 4^j$, the school method’s count: $K(2^k) = 3^{k-j} 4^j$.

**Exercise 21.10 ★★★.**

Show that the [median of medians](#def-b1-divide-and-conquer-selection) with groups of three gives the recurrence $T(n) \leq T(n/3) + T(2n/3) + an$, and that this recurrence does not imply $T(n) = O(n)$: its solution with equality is $\Theta(n \log n)$.

**Solution of Exercise 21.10.**

With groups of three, at least half of the $n/3$ medians are at most the pivot, and each of their groups holds two keys at most the pivot: about $n/3$ keys on each side, so the recursive call receives up to $2n/3$, and $T(n) \leq T(n/3) +
T(2n/3) + an$. Now $1/3 + 2/3 = 1$: no level of the [recursion tree](https://one-course.com/books/computer-science/3/en/chapter/13-asymptotic-analysis-and-recurrences#def-b1-asymptotic-analysis-recurrence) is smaller than the one above. Take $T(n) = T(n/3) +
T(2n/3) + an$ and suppose $T(j) \geq a j \log_3 j$ for $j < n$. Then

$$
T(n) \geq a\tfrac n3 \log_3 \tfrac n3 + a\tfrac{2n}{3} \log_3 \tfrac{2n}{3} + an = an \log_3 n - a\tfrac n3 -
a\tfrac{2n}3 + a\tfrac{2n}3 \log_3 2 + an \geq an \log_3 n,
$$

so $T(n) = \Omega(n \log n)$; with groups of three the method is not proved linear.

**Exercise 21.11 ★★★.**

Buildings are rectangles $(\mathit{left}, \mathit{right}, \mathit{height})$ standing on a line. Compute the skyline, the list of points where the visible height changes, by [divide and conquer](#def-b1-divide-and-conquer-dc) in $O(n \log n)$.

**Solution of Exercise 21.11.**

```python
def skyline(buildings):
    if not buildings:
        return []
    if len(buildings) == 1:
        left, right, h = buildings[0]
        return [(left, h), (right, 0)]
    mid = len(buildings) // 2
    return merge(skyline(buildings[:mid]), skyline(buildings[mid:]))


def merge(a, b):
    """Merge two outlines: at each x, the higher of the two current heights."""
    out, i, j, ha, hb = [], 0, 0, 0, 0
    while i < len(a) or j < len(b):
        xa = a[i][0] if i < len(a) else float("inf")
        x = min(xa, b[j][0] if j < len(b) else float("inf"))
        if i < len(a) and a[i][0] == x:
            ha = a[i][1]
            i += 1
        if j < len(b) and b[j][0] == x:
            hb = b[j][1]
            j += 1
        h = max(ha, hb)
        if not out or out[-1][1] != h:
            out.append((x, h))
    return out
```

*The skyline code/bachelor-1/21-divide-and-conquer/exercises/skyline.py*

Merging two outlines walks both lists once, keeping the current height of each, and records the larger one wherever it changes: $\Theta(n)$ for outlines of $O(n)$ points. Hence $T(n) = 2T(n/2) + \Theta(n) = \Theta(n \log n)$. The test compares the outline’s height at every integer abscissa with the highest building standing there.

**Exercise 21.12 ★★★.**

Find four positions $i < j < k < m$ of a list whose keys sum to a target in $O(n^2 \log n)$, by meeting in the middle on the sums of pairs, and prove the method correct.

**Solution of Exercise 21.12.**

```python
def four_sum(a, target):
    """Positions (i, j, k, m), i < j < k < m, of a solution, or None."""
    n = len(a)
    latest = {}  # sum -> the pair (k, m) with that sum and the largest k
    for k in range(n):
        for m in range(k + 1, n):
            latest[a[k] + a[m]] = (k, m)  # k grows: the last kept is the latest
    sums = sorted(latest)
    for i in range(n):
        for j in range(i + 1, n):
            want = target - a[i] - a[j]
            p = bisect_left(sums, want)
            if p < len(sums) and sums[p] == want and latest[want][0] > j:
                return (i, j) + latest[want]
    return None
```

*Four keys with a given sum code/bachelor-1/21-divide-and-conquer/exercises/four_sum.py*

The table keeps, for each sum of two keys, the pair $(k, m)$ with that sum and the largest $k$. If a solution $i < j < k
< m$ exists, then when the loops reach $(i, j)$, the sum $a[k] + a[m]$ is in the table with a pair whose first position is at least $k > j$: a solution is returned. Conversely a returned quadruple has the target sum and increasing positions. The table takes $\Theta(n^2)$ steps, its sorting $O(n^2 \log n)$, and the $n(n - 1)/2$ binary searches $O(n^2 \log
n)$. The test compares with all quadruples on random lists.

## 21.7 Problem: Multiplying long numbers

**Problem 21.1.**

Weekend problem — Multiplying long numbers

The listings of this chapter multiply numbers given as lists of decimal digits. The problem counts their work exactly, then reads their measured times (Outputs [21.2](#out-b1-divide-and-conquer-karatsuba) and [21.3](#out-b1-divide-and-conquer-timing)).

**Part I — The school method.**

1. How many digit products does the school method make for two numbers of $n$ digits? Check with the output.
2. Show that a cell of `r` , before the carries, holds at most $81n$ .
3. Show that propagating the carries once, at the end, costs $\Theta(n)$ and gives the right digits.
4. Why does the result of two $n$ -digit numbers fit in $2n$ digits?
5. By what factor does the school method’s time grow when $n$ doubles, according to the table? What does the model predict?
6. How many digit products does the opening’s multiplication of two 1000-digit numbers take?

**Part II — Karatsuba’s identity.**

7. Expand $ab$ with $a = a_1 10^m + a_0$ , $b = b_1 10^m + b_0$ .
8. Prove $a_1 b_0 + a_0 b_1 = a_1 b_1 + a_0 b_0 - (a_1 - a_0)(b_1 - b_0)$ .
9. Why do $|a_1 - a_0|$ and $|b_1 - b_0|$ have at most $m$ digits?
10. What does `difference` return, and why does it compare from the top digit?
11. The combine loop leaves cells that may be negative. Why does `normalise` still give the right digits?
12. Write the recurrence for the number $K(n)$ of digit products, $n$ a power of 2.

**Part III — Exact counts.**

13. Prove $K(2^k) = 3^k$ .
14. Show that $3^k = n^{\log_2 3}$ for $n = 2^k$ .
15. Compare $K(1024)$ with $1024^2$ .
16. Show that the other work of one call on $n$ digits is $\Theta(n)$ , and that the total work is still $\Theta(n^{\log_2 3})$ .
17. With a cutoff $c = 2^j$ , how many digit products are made on $2^k$ digits ( [Exercise 21.9](#exo-b1-divide-and-conquer-9) )? Give the count for $n = 1024$ and $c = 32$ .
18. Which cutoff minimises the number of digit products? Why is a larger one used anyway?

**Part IV — Where it pays, on this machine.**

19. Without a cutoff, by what factor is Karatsuba’s method slower than the school method at each $n$ of the table? How does that factor change when $n$ doubles?
20. Estimate from that trend the size from which Karatsuba’s method without a cutoff would win.
21. From which $n$ of the table does Karatsuba’s method with cutoff 8, then with cutoff 32, beat the school method?
22. By what factor does the time with cutoff 32 grow when $n$ doubles at the end of the table? Compare with $3$ and $4$ .
23. CPython’s cutoff is 70 digits of 30 bits. How many decimal digits is that?
24. State the named result, *Karatsuba’s count* .

**Solution of Problem 21.1.**

**1.** $n^2$, one for each pair of digits: 1 048 576 for $n = 1024$.

**2.** Cell $t$ receives the products $a_i b_j$ with $i + j = t$: at most one $j$ for each $i$, so at most $n$ products, each at most $9 \times 9 = 81$.

**3.** One pass over $2n$ cells, with a carry at most $(81n + \mathit{carry})/10 < 9n$: $\Theta(n)$ steps on numbers of a few bytes. Each step replaces $r_t + \mathit{carry}$ by its last digit and carries the rest to cell $t + 1$, which keeps $\sum_t r_t 10^t$ unchanged; at the end every cell is a digit.

**4.** $a, b < 10^n$, so $ab < 10^{2n}$.

**5.** From 9412 to 39 270 to 167 668: by about 4.2 per doubling; the model predicts 4.

**6.** A million, $1000^2$; the program pads to 1024 digits and makes 1 048 576.

**7.** $ab = a_1 b_1 10^{2m} + (a_1 b_0 + a_0 b_1) 10^m + a_0 b_0$.

**8.** $(a_1 - a_0)(b_1 - b_0) = a_1 b_1 - a_1 b_0 - a_0 b_1 + a_0 b_0$; move the two middle terms to the other side.

**9.** $0 \leq a_0, a_1 < 10^m$, so $|a_1 - a_0| < 10^m$.

**10.** The digits of $|x - y|$, as a list of the same length, and the sign of $x - y$. Between two numbers of the same length, the first digit that differs from the top decides which is larger.

**11.** The loop makes $\sum_t r_t 10^t$ equal to the product. `divmod` writes any integer, negative or not, as $10q + d$ with $0 \leq d \leq 9$, so each step keeps the sum and leaves a digit; the product is in $[0, 10^{2n})$, so the last carry is 0 and the cells are its digits.

**12.** $K(1) = 1$ and $K(n) = 3K(n/2)$.

**13.** $K(2^0) = 1 = 3^0$, and $K(2^{k+1}) = 3K(2^k) = 3 \cdot 3^k = 3^{k+1}$.

**14.** $3^k = 2^{k \log_2 3} = (2^k)^{\log_2 3} = n^{\log_2 3}$.

**15.** $3^{10} = 59\,049$ against 1 048 576: about 18 times fewer.

**16.** The slices, the two differences, the combine loop and `normalise` each take $\Theta(n)$ steps. So $W(n) = 3W(n/2) + \Theta(n)$, and since $3 > 2^1$ the master theorem gives $\Theta(n^{\log_2 3})$: the leaves dominate, and the additions do not change the order.

**17.** $3^{k-j} 4^j$; for $n = 1024$ and $c = 32$, $3^5 \cdot 4^5 = 248\,832$.

**18.** The cutoff 1: each level handed to the school method multiplies the count by $4/3$. A larger cutoff is used because a call, with its lists and its carries, costs far more than a digit product: the time is not the count.

**19.** 12.3, 10.8, 8.1, 6.9, 5.1, 2.8, 2.0, 1.4 for $n = 16$ to 2048. The factor falls by about 0.7 per doubling at the end, close to the $3/4$ expected when one time grows like $3^k$ and the other like $4^k$.

**20.** With factors of about $1.4 \times 0.75 \approx 1.06$ at 4096 digits and 0.8 at 8192: from about 5000 digits.

**21.** With cutoff 8, from 256 digits (1534 against 1773 microseconds); with cutoff 32, from 64 digits (99 against 113).

**22.** $29\,815 / 9772 \approx 3.05$ and $9772 / 3204 \approx 3.05$: close to 3, where the school method grows by 4.

**23.** $70 \times 30 = 2100$ bits, and $2100 \log_{10} 2 \approx 632$ decimal digits.

**24.** *Karatsuba’s count*: Karatsuba’s method multiplies two numbers of $2^k$ digits with exactly $3^k$ digit products, that is $n^{\log_2 3} \approx n^{1.585}$ for $n = 2^k$ (questions 12 to 14), the counts printed by the program in [Output 21.2](#out-b1-divide-and-conquer-karatsuba); its whole cost is $\Theta(n^{\log_2 3})$ (question 16).
