---
title: "Asymptotic Analysis and Recurrences"
book: "University Computer Science — Year 1"
subject: computer-science
language: en
chapter: 13
exercises: 12
source: https://one-course.com/books/computer-science/3/en/chapter/13-asymptotic-analysis-and-recurrences
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 13 — Asymptotic Analysis and Recurrences

Two programs sort thirty million records, and both are correct. On a machine that performs a billion [elementary operations](#def-b1-asymptotic-analysis-ram) a second, the first finishes in under a second and the second runs for more than ten days. Neither the language nor the machine makes the difference: the first does about $n \log_2 n$ operations and the second about $n^2$. This chapter makes such statements precise: what is counted, how [costs](#def-b1-asymptotic-analysis-cost) are compared when $n$ grows, how the [cost](#def-b1-asymptotic-analysis-cost) of an algorithm differs between its best, worst and average inputs, and how to solve the recurrences that the [cost](#def-b1-asymptotic-analysis-cost) of a recursive algorithm obeys.

**You already know.**

For sequences $u$ and $v$ of positive reals, $\lim u_n/v_n = 0$ means that $u$ becomes negligible beside $v$. For $a > 0$ and $b > 1$: $(\log n)/n^a \to 0$, $n^a/b^n \to 0$ and $b^n/n! \to 0$. The sum $1 + 2 + \dots + n = n(n + 1)/2$, and $1 + q + \dots + q^{m - 1} = (q^m - 1)/(q - 1)$ for $q \neq 1$. Insertion sort inserts each element into the sorted part before it, shifting the larger elements one place to the right.

## 13.1 What the model counts

**Definition 13.1 (Model of computation, elementary operation).**

The *RAM model* is a model of computation: an idealised machine with a memory of numbered cells, each holding a machine word, in which each *elementary operation* [costs](#def-b1-asymptotic-analysis-cost) one unit of time — an arithmetic operation or a comparison on words, reading or writing a cell, a jump. Words have $\Theta(\log n)$ bits for inputs of size $n$, enough to index the input.

**Definition 13.2 (Input size, cost function).**

The *input size* $n$ is a natural number measuring an input: the length of a list, the number of vertices and edges of a graph, the number of bits of an integer. The *cost* of an algorithm on an input is the number of [elementary operations](#def-b1-asymptotic-analysis-ram) it performs; a *cost function* gives a cost for each size.

Counting every operation is tedious and depends on details of the translation to machine code, so in practice one counts a single operation that dominates: the comparisons of a sort, the multiplications of an arithmetic algorithm. The other operations are at most a constant multiple of it. A counter added to the program makes the count observable.

```python
def insertion_sort(a):
    """Sorts a in place and returns the number of comparisons between elements."""
    comparisons = 0
    for i in range(1, len(a)):
        key, j = a[i], i - 1
        while j >= 0:
            comparisons += 1
            if a[j] <= key:
                break
            a[j + 1] = a[j]
            j -= 1
        a[j + 1] = key
    return comparisons
```

***Listing 13.1.** Insertion sort, counting its comparisons code/bachelor-1/13-asymptotic-analysis/listings/count_ops.py*

```
$ python count_ops.py
    n  sorted  reversed  random  n(n-1)/4
    8       7        28      19        14
   16      15       120      48        60
   32      31       496     280       248
   64      63      2016    1104      1008
  128     127      8128    3883      4064
  256     255     32640   16308     16320
  512     511    130816   65014     65408
```

***Output 13.1.** Comparisons on a sorted, a reversed and a shuffled list.*

On a sorted list, each insertion stops at its first comparison: $n - 1$ comparisons. On a reversed list, the $i$-th insertion goes to the front, with $i$ comparisons: $1 + 2 + \dots + (n - 1) = n(n - 1)/2$. A shuffled list lands near $n(n - 1)/4$, which [Section 13.3](#sec-13-3) explains. Constants are dropped for two reasons: they depend on the machine and the [compiler](https://one-course.com/books/computer-science/3/en/chapter/1-from-source-code-to-a-running-program#def-b1-compilation-pipeline-compiler), which the model abstracts away, and they matter less than the growth as soon as $n$ is large. The model also hides the memory hierarchy: on a real machine, an access to a cell far from the last ones [costs](#def-b1-asymptotic-analysis-cost) much more than a comparison, which the second year studies.

## 13.2 $O$, $\Omega$ and $\Theta$

**Definition 13.3 (Big O, big Omega, big Theta).**

Let $f, g : \mathbb{N} \to \mathbb{R}_+$. Then $f \in O(g)$ if there are a constant $c > 0$ and a rank $n_0$ with $f(n) \leq c\,g(n)$ for all $n \geq n_0$; $f \in \Omega(g)$ if $g \in O(f)$, that is $f(n) \geq
c\,g(n)$ from some rank on for some $c > 0$; and $f \in \Theta(g)$ if both hold.

One often writes $f = O(g)$; the equality sign is then read as “belongs to”. The constant $c$ and the rank $n_0$ are chosen once, before $n$: [Exercise 13.5](#exo-b1-asymptotic-analysis-5) shows what goes wrong otherwise. If $f(n)/g(n)$ has a limit $\ell$, then $\ell < \infty$ gives $f \in O(g)$, and $0 < \ell < \infty$ gives $f \in \Theta(g)$.

**Proposition 13.4 (Rules for O).**

For [cost functions](#def-b1-asymptotic-analysis-cost) $f_1 \in O(g_1)$ and $f_2 \in O(g_2)$: $f_1 + f_2 \in O(\max(g_1, g_2))$ and $f_1 f_2 \in O(g_1
g_2)$; if moreover $g_1 \in O(h)$, then $f_1 \in O(h)$. The same rules hold for $\Omega$ and $\Theta$.

**Proof.** With $f_1 \leq c_1 g_1$ from $n_1$ on and $f_2 \leq c_2 g_2$ from $n_2$ on: from $\max(n_1, n_2)$ on, $f_1 + f_2 \leq
(c_1 + c_2) \max(g_1, g_2)$ and $f_1 f_2 \leq c_1 c_2\, g_1 g_2$. For transitivity, $g_1 \leq c\,h$ from some rank on gives $f_1 \leq c_1 c\, h$. ∎

The sum rule says that a sequence of steps [costs](#def-b1-asymptotic-analysis-cost) as much as its most expensive step, and the product rule that a loop [costs](#def-b1-asymptotic-analysis-cost) its number of iterations times the [cost](#def-b1-asymptotic-analysis-cost) of one iteration, when that [cost](#def-b1-asymptotic-analysis-cost) does not depend on the iteration.

**Proposition 13.5 (The scale of growth).**

For $a > 0$ and $b > 1$, as $n \to \infty$: $\log n \in O(n^a)$, $n^a \in O(b^n)$ and $b^n \in O(n!)$, and none of these is a $\Theta$. Moreover $\log_b n \in \Theta(\log_2 n)$, so the base of a logarithm does not matter inside $O$.

**Proof.** The three limits recalled at the start of the chapter are 0, which gives each $O$ and excludes each $\Theta$. And $\log_b n = \log_2 n / \log_2 b$ is a constant multiple. ∎

```
$ python growth.py
   n log2 n n log2 n    n^2     n^3                  2^n
   2      1        2      4       8                    4
   4      2        8     16      64                   16
   8      3       24     64     512                  256
  16      4       64    256    4096                65536
  32      5      160   1024   32768           4294967296
  64      6      384   4096  262144 18446744073709551616
n log2 n: 7.45e+08 operations, 0.7 s = 0.00 days
     n^2: 9.00e+14 operations, 900,000.0 s = 10.42 days
```

***Output 13.2.** The usual [cost functions](#def-b1-asymptotic-analysis-cost), and the two programs of the opening at thirty million records and a billion operations a second.*

![The usual cost functions on a logarithmic scale. Powers of n become straight lines of increasing slope on a log–log plot; here, with n on a linear axis, the exponential 2n is the straight line, and it crosses every power of n eventually.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-asymptotic-analysis/fig-acbe7e94d42e.svg)

*The usual [cost functions](#def-b1-asymptotic-analysis-cost) on a logarithmic scale. Powers of $n$ become straight lines of increasing slope on a log–log plot; here, with $n$ on a linear axis, the exponential $2^n$ is the straight line, and it crosses every power of $n$ eventually.*

$O$ is only an upper bound. “Merge sort is in $O(n^3)$” is true and useless; “insertion sort is in $O(n^2)$” holds for every input, including the sorted ones that it finishes in $n - 1$ comparisons. A lower bound needs $\Omega$, and a precise statement needs $\Theta$, with the [input class](https://one-course.com/books/computer-science/3/en/chapter/7-modular-programs-makefiles-and-tests#def-b1-c-modules-make-tests-input-class) it is about.

## 13.3 Worst, best and average case

**Definition 13.6 (Worst-case, best-case and average-case cost).**

For an algorithm whose [cost](#def-b1-asymptotic-analysis-cost) on an input $x$ is $C(x)$, and $I_n$ the finite set of inputs of size $n$ considered, the *worst-case cost* is $\max_{x \in I_n} C(x)$, the *best-case cost* is $\min_{x \in I_n} C(x)$, and the *average-case cost* is $\frac{1}{|I_n|}\sum_{x \in I_n}
C(x)$.

For a comparison sort on distinct keys, only the order of the keys matters, so $I_n$ can be taken as the $n!$ orders of $0, \dots, n - 1$. For insertion sort, the best case is $n - 1$ and the worst $n(n - 1)/2$; the average needs a count.

**Proposition 13.7 (Average cost of insertion sort).**

Over the $n!$ orders of $n$ distinct keys, insertion sort makes on average exactly $\frac{n(n - 1)}{4} + n - H_n$ comparisons, where $H_n = 1 + \frac12 + \dots + \frac1n$. This is in $\Theta(n^2)$.

**Proof.** An *inversion* of an order is a pair of positions $i < j$ whose keys are in decreasing order. In insertion sort, each comparison either shifts an element, which removes exactly one inversion, or stops the inner loop. The inner loop stops on a comparison unless the key reaches the front, which happens exactly when the key is smaller than every key before it, a *left-to-right minimum*. So an order with $I$ inversions and $L$ left-to-right minima (the first key counts) [costs](#def-b1-asymptotic-analysis-cost) $C = I + (n - 1) - (L - 1)$.

Average of $I$: exchanging the keys at two positions $i < j$ is a one-to-one correspondence between the orders where the pair is inverted and those where it is not, so each of the $\binom{n}{2}$ pairs is inverted in exactly half of the orders: the total of $I$ is $n! \binom{n}{2}/2$, and the average $n(n - 1)/4$. Average of $L$: position $i$ (from 0) holds a left-to-right minimum when it holds the smallest of the first $i + 1$ keys; grouping the orders by the set of those keys and the arrangement of the rest, that smallest key is at each of the $i + 1$ positions equally often, so in exactly $1/(i + 1)$ of the orders. Summing over $i$, the average of $L$ is $H_n$, and the average [cost](#def-b1-asymptotic-analysis-cost) is $n(n - 1)/4 +
(n - 1) - (H_n - 1)$. As $H_n \leq n$, it lies between $n(n - 1)/4$ and $n(n + 3)/4$. ∎

```
$ python inversions.py
 n orders   average  n(n-1)/4 + n - H_n
 1      1         0                   0
 2      2         1                   1
 3      6       8/3                 8/3
 4     24     59/12               59/12
 5    120    463/60              463/60
 6    720    221/20              221/20
 7   5040  2087/140            2087/140
 8  40320  5399/280            5399/280
```

***Output 13.3.** The average over all orders, as an exact fraction, against the formula, for $n \leq 8$.*

**Definition 13.8 (Space cost).**

The *space cost* of an algorithm is the number of memory cells it uses beyond its input, at its peak, as a function of the [input size](#def-b1-asymptotic-analysis-cost); the [stack frames](https://one-course.com/books/computer-science/3/en/chapter/3-functions-and-the-call-stack#def-b1-c-functions-and-stack-call-stack) of recursive calls count.

Insertion sort uses $\Theta(1)$ cells beyond the list: it sorts *in place*. A merge sort that copies its halves uses $\Theta(n)$ cells, and the recursion of a binary search uses $\Theta(\log n)$ frames where the loop of [Chapter 12](https://one-course.com/books/computer-science/3/en/chapter/12-program-correctness#ch-b1-program-correctness) uses $\Theta(1)$.

## 13.4 Sums

Nested loops give sums. A double loop over $0 \leq i < j < n$ performs $\binom{n}{2} = n(n - 1)/2$ iterations; a triple loop over $i < j < k$ performs $\binom{n}{3}$ ([Exercise 13.7](#exo-b1-asymptotic-analysis-7)). A loop that doubles $j$ from 1 until $n$ runs $\lceil \log_2 n \rceil$ times. Three tools bound the sums that have no closed form.

**Method 13.9 (Bounding a sum).**

1. *Bound each term by the largest* : $\sum_{i=1}^{n} f(i) \leq n \max_i f(i)$ , an upper bound.
2. *Split* : for $f$ increasing, the $\lceil n/2 \rceil$ terms from $i = \lfloor n/2 \rfloor + 1$ on are at least $f(n/2)$ , so $\sum_{i=1}^n f(i) \geq \frac{n}{2} f(\frac{n}{2})$ , a lower bound of the same order as the upper one when $f(n/2) \in \Theta(f(n))$ .
3. *Compare with an integral* : for $f$ decreasing on $[1, \infty)$ , $\int_1^{n + 1} f \leq \sum_{i=1}^n f(i) \leq f(1) + \int_1^n f$ .

**Proposition 13.10 (Harmonic numbers and log⁡n!\log n!logn!).**

$\ln(n + 1) \leq H_n \leq 1 + \ln n$, so $H_n \in \Theta(\log n)$; and $\log_2 n! \in \Theta(n \log n)$.

**Proof.** The integral of $1/x$ from 1 to $n + 1$ is $\ln(n + 1)$, and from 1 to $n$ it is $\ln n$; the third rule gives the first claim. For the second, $\log_2 n! = \sum_{i=1}^n \log_2 i \leq n \log_2 n$ by the first rule, and $\geq \frac{n}{2}
\log_2 \frac{n}{2} = \frac{n}{2}(\log_2 n - 1)$ by the second, which is at least $\frac{n}{4}\log_2 n$ for $n \geq 4$. ∎

The harmonic number thus contributes only $\Theta(\log n)$ to the average of insertion sort, and $\log_2 n!$ will be the number of comparisons that any comparison sort needs in the worst case ([Chapter 19](https://one-course.com/books/computer-science/3/en/chapter/19-sorting#ch-b1-sorting)).

## 13.5 Recurrences

**Definition 13.11 (Recurrence relation, recursion tree).**

A *recurrence relation* defines a [cost function](#def-b1-asymptotic-analysis-cost) by its values on small sizes and an equation expressing $T(n)$ in terms of values on smaller sizes. The *recursion tree* of such an equation has a node for each call, labelled with the [cost](#def-b1-asymptotic-analysis-cost) spent in that call outside its recursive calls; its children are the calls it makes. $T(n)$ is the sum of all the labels, which one often computes level by level.

A recursive algorithm gives a recurrence directly: binary search halves its interval with one comparison, $T(n) =
T(n/2) + 1$; merge sort sorts two halves and merges them with at most $n$ comparisons, $T(n) = 2T(n/2) + n$. Three methods solve them. *Unrolling* substitutes the equation into itself: $T(n) = T(n/2) + 1 = T(n/4) + 2 = \dots =
T(1) + \log_2 n$ for $n$ a power of 2. The *[recursion tree](#def-b1-asymptotic-analysis-recurrence)* sums level by level. And one can *guess and prove by induction*, the guess coming from either method or from computed values.

![The recursion tree of T(n) = 2T(n/2) + n: every level costs n, and there are _2 n levels above the leaves, hence T(n) = n _2 n + nT(1) for n a power of 2.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-asymptotic-analysis/fig-47233c559fd1.svg)

*The [recursion tree](#def-b1-asymptotic-analysis-recurrence) of $T(n) = 2T(n/2) + n$: every level [costs](#def-b1-asymptotic-analysis-cost) $n$, and there are $\log_2 n$ levels above the leaves, hence $T(n) = n\log_2 n + nT(1)$ for $n$ a power of 2.*

```
$ python recurrences.py
    n  T1     T2      T3       T4   closed forms
    1   0      0       1        1   all equal
    4   2      8      19       28   all equal
   16   4     64     211      496   all equal
   64   6    384    2059     8128   all equal
  256   8   2048   19171   130816   all equal
 1024  10  10240  175099  2096128   all equal
```

***Output 13.4.** Four recurrences computed exactly for $n$ a power of 2, each equal to its closed form: $T_1 = \log_2 n$, $T_2 = n\log_2 n$, $T_3 = 3n^{\log_2 3} - 2n$ and $T_4 =
2n^2 - n$.*

The forms of $T_3$ and $T_4$ come from the proof below; checking them by induction is short. For $T_4$: $T_4(1) = 1 = 2
- 1$, and $4(2(n/2)^2 - n/2) + n = 2n^2 - 2n + n = 2n^2 - n$.

**Theorem 13.12 (Master theorem).**

Let $a \geq 1$, $b \geq 2$ an integer, $k \geq 0$, and $T$ defined on the powers of $b$ by $T(1) > 0$ and $T(n) =
aT(n/b) + n^k$. Then

$$
T(n) \in \begin{cases} \Theta(n^k) & \text{if } a < b^k \quad\text{(the root dominates)},\\
\Theta(n^k \log n) & \text{if } a = b^k \quad\text{(every level costs the same)},\\
\Theta(n^{\log_b a}) & \text{if } a > b^k \quad\text{(the leaves dominate)}. \end{cases}
$$

**Proof.** Let $n = b^m$. Unrolling, level $i$ of the [recursion tree](#def-b1-asymptotic-analysis-recurrence) has $a^i$ nodes of size $n/b^i$, each costing $(n/b^i)^k$, and the $a^m$ leaves [cost](#def-b1-asymptotic-analysis-cost) $T(1)$ each:

$$
T(n) = a^m T(1) + \sum_{i=0}^{m-1} a^i \Bigl(\frac{n}{b^i}\Bigr)^k = a^m T(1) + n^k \sum_{i=0}^{m-1} q^i, \qquad q =
\frac{a}{b^k}.
$$

Note that $a^m = b^{m \log_b a} = n^{\log_b a}$. If $a < b^k$, then $q < 1$ and $1 \leq \sum q^i \leq 1/(1 - q)$; and $\log_b a < k$, so $a^m T(1) \leq T(1) n^k$; hence $n^k \leq T(n) \leq (T(1) + 1/(1 - q))\, n^k$. If $a > b^k$, then $q > 1$ and $n^k \sum_{i<m} q^i = n^k (q^m - 1)/(q - 1) = (a^m - n^k)/(q - 1)$, between 0 and $a^m/(q - 1)$; so $T(1)\,
a^m \leq T(n) \leq (T(1) + 1/(q - 1))\, a^m$. The case $a = b^k$ is [Exercise 13.10](#exo-b1-asymptotic-analysis-10). ∎

**Remark 13.13.**

Algorithms split $n$ into $\lfloor n/b \rfloor$ and $\lceil n/b \rceil$ parts, and their combining [costs](#def-b1-asymptotic-analysis-cost) are $c\,n^k$ plus lower terms. The conclusions still hold for such recurrences when $T$ is increasing: $T(n)$ lies between its values at the powers of $b$ around $n$, which are within a constant factor of each other. [Exercise 13.11](#exo-b1-asymptotic-analysis-11) treats merge sort’s recurrence with floors and ceilings exactly.

```python
def master(a, b, k):
    """For a >= 1, b >= 2, k >= 0: the case, the order of T, and a function g
    with T in Theta(g)."""
    if a < b**k:
        return "root", f"n^{k}", lambda n: n**k
    if a == b**k:
        return "even", f"n^{k} log n", lambda n: n**k * log(n, b)
    e = log(a, b)
    return "leaves", f"n^{e:.3f}", lambda n: n**e
```

***Listing 13.2.** The three cases code/bachelor-1/13-asymptotic-analysis/listings/master.py*

```
$ python master.py
                    a b k    case  Theta       T/g at 2^10, 2^20
     binary search  1 2 0    even  n^0 log n    1.100  1.050
        merge sort  2 2 1    even  n^1 log n    1.100  1.050
         Karatsuba  3 2 1  leaves  n^1.585      2.965  2.999
    eight products  8 2 2  leaves  n^3.000      1.999  2.000
          Strassen  7 2 2  leaves  n^2.807      2.328  2.333
square at the root  2 2 2    root  n^2          1.999  2.000
```

***Output 13.5.** The cases on six recurrences, and the ratio of the exact $T(n)$, with $T(1) = 1$, to the predicted order at $2^{10}$ and $2^{20}$: it settles to a constant.*

Karatsuba’s multiplication of $n$-digit numbers replaces four half-size products by three, which moves the [cost](#def-b1-asymptotic-analysis-cost) from $\Theta(n^2)$ to $\Theta(n^{\log_2 3}) \approx \Theta(n^{1.585})$; Strassen’s product of matrices replaces eight half-size products by seven, from $\Theta(n^3)$ to $\Theta(n^{2.807})$. Both are leaf-dominated: the count of subproblems matters more than the [cost](#def-b1-asymptotic-analysis-cost) of combining them. The ratio for merge sort, $1 + 1/\log_2 n$, shows how slowly the lower term fades.

![The three regimes of the master theorem, drawn as the cost of each level of the recursion tree (one bar per level, from the root down). The level costs form a geometric sequence of ratio a/bk: decreasing, the root’s term dominates; constant, the _b n levels add up; increasing, the leaves dominate.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-asymptotic-analysis/fig-2315c126946c.svg)

*The three regimes of the master theorem, drawn as the [cost](#def-b1-asymptotic-analysis-cost) of each level of the [recursion tree](#def-b1-asymptotic-analysis-recurrence) (one bar per level, from the root down). The level [costs](#def-b1-asymptotic-analysis-cost) form a geometric sequence of ratio $a/b^k$: decreasing, the root’s term dominates; constant, the $\log_b n$ levels add up; increasing, the leaves dominate.*

## 13.6 Counts and times

A count predicts a time if each counted operation [costs](#def-b1-asymptotic-analysis-cost) about the same. The *doubling test* checks the order of a [cost](#def-b1-asymptotic-analysis-cost) from measurements alone: double $n$ and look at the ratio of the [costs](#def-b1-asymptotic-analysis-cost). For a [cost](#def-b1-asymptotic-analysis-cost) $c\,n^2$ plus lower terms the ratio tends to 4, for $c\,n$ to 2, and for $c\,n \log_2 n$ it equals $2(1 + 1/\log_2 n)$, slightly above 2 and tending to 2. The weekend problem proves these, and shows that a $\Theta$ class alone is not enough: a [cost](#def-b1-asymptotic-analysis-cost) in $\Theta(n)$ can have a ratio that never settles.

```python
rng = random.Random(2026)
previous = None
print(f"{'n':>5} {'maximum':>8} {'merge sort':>10} {'insertion':>10}   ratios")
for n in [500, 1000, 2000, 4000, 8000]:
    a = rng.sample(range(10 * n), n)
    c_max, c_merge = [0], [0]
    maximum(a, c_max)
    merge_sort(a, c_merge)
    counts = (c_max[0], c_merge[0], insertion_sort(list(a)))
    ratios = "" if previous is None else " ".join(
        f"{c / p:5.2f}" for c, p in zip(counts, previous))
    print(f"{n:5d} {counts[0]:8d} {counts[1]:10d} {counts[2]:10d}   {ratios}".rstrip())
    previous = counts
```

***Listing 13.3.** Counts of three algorithms as $n$ doubles code/bachelor-1/13-asymptotic-analysis/listings/doubling.py*

```
$ python doubling.py
    n  maximum merge sort  insertion   ratios
  500      499       3847      66704
 1000      999       8727     256421    2.00  2.27  3.84
 2000     1999      19374     987402    2.00  2.22  3.85
 4000     3999      42840    3988459    2.00  2.21  4.04
 8000     7999      93609   16180928    2.00  2.19  4.06
```

***Output 13.6.** Comparisons of the maximum, merge sort and insertion sort on shuffled lists, then the ratios to the previous row.*

```
$ python timing.py
    n  max (ms) merge (ms)  ins. (ms)   ratios
  500     0.028      0.375        2.3
 1000     0.057      0.818       10.1    2.02  2.18  4.39
 2000     0.117      1.846       39.9    2.07  2.26  3.94
 4000     0.260      4.627      165.4    2.23  2.51  4.15
 8000     0.480      8.746      635.7    1.85  1.89  3.84
```

***Output 13.7.** The same three algorithms timed on the author’s laptop, best of five runs, in milliseconds, then the ratios.*

![Time divided by count, from the two outputs above: nearly flat for each algorithm, so the count predicts the time up to a constant, which differs between algorithms (a merge step allocates and appends, an insertion step only compares and moves).](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-asymptotic-analysis/fig-f3b4e13bc70a.svg)

*Time divided by count, from the two outputs above: nearly flat for each algorithm, so the count predicts the time up to a constant, which differs between algorithms (a merge step allocates and appends, an insertion step only compares and moves).*

The time ratios scatter around the count ratios: a measurement on a real machine includes caches, the [interpreter](https://one-course.com/books/computer-science/3/en/chapter/1-from-source-code-to-a-running-program#def-b1-compilation-pipeline-interpreter) and the other programs running at the same time. The counts are exact and repeatable; the times say what the counts [cost](#def-b1-asymptotic-analysis-cost) on one machine.

**In practice.**

To estimate an unknown [cost](#def-b1-asymptotic-analysis-cost), run the program for sizes $n, 2n, 4n, \dots$ until the time is a second or more, and look at the ratios. A ratio near 2 suggests linear time; near 4 quadratic; near 8 cubic. A ratio that keeps growing suggests exponential time, and the end of the experiment.

## 13.7 Exercises

**Exercise 13.1 ★.**

Predict what the program prints, and give the two counts as functions of the bounds 10 and 1000.

```python
count = 0
for i in range(10):
    for _j in range(i, 10):
        count += 1
print(count)

k, steps = 1, 0
while k < 1000:
    k, steps = 2 * k, steps + 1
print(k, steps)
```

***Listing 13.4.** Two counts code/bachelor-1/13-asymptotic-analysis/listings/exo_count.py*

**Solution of Exercise 13.1.**

```
55
1024 10
```

***Output 13.10.** The two counts. Some lines are left out.*

For each $i$ the inner loop runs $10 - i$ times: $10 + 9 + \dots + 1 = 55 = 10 \cdot 11/2$, in general $n(n + 1)/2$. The second loop doubles $k$ until it reaches 1000: $k = 2^{10} = 1024$ after 10 steps, in general $\lceil \log_2 N
\rceil$ steps for a bound $N$ that is not a power of 2.

**Exercise 13.2 ★.**

Order by growth, from slowest to fastest: $n^2 \log n$, $(\log n)^{10}$, $1.01^n$, $\sqrt{n}$, $n^{2.5}$. Justify each step with [Proposition 13.5](#prop-b1-asymptotic-analysis-scale).

**Solution of Exercise 13.2.**

$(\log n)^{10} \ll \sqrt{n} \ll n^2 \log n \ll n^{2.5} \ll 1.01^n$. First, $(\log n)^{10}/\sqrt{n} = (\log n /
n^{1/20})^{10} \to 0$. Then $\sqrt{n}/(n^2 \log n) \to 0$ trivially. Next $n^2 \log n / n^{2.5} = \log n / n^{0.5} \to
0$. Last, $n^{2.5}/1.01^n \to 0$ since $1.01 > 1$.

**Exercise 13.3 ★.**

With $T(1) = 1$ and $T(n) = 2T(n/2) + 1$, compute $T(16)$, guess a closed form, and prove it.

**Solution of Exercise 13.3.**

$T(2) = 3$, $T(4) = 7$, $T(8) = 15$, $T(16) = 31$. Guess $T(n) = 2n - 1$: true for $n = 1$, and $2(2 \cdot \frac n2 - 1) + 1
= 2n - 1$. It is $\Theta(n)$, the [leaf](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) case of the master theorem ($a = 2 > 2^0$).

**Exercise 13.4 ★.**

Which case of the master theorem applies, and what is the order of $T$? (a) $T(n) = 4T(n/2) + n$. (b) $T(n) = 4T(n/2)
+ n^2$. (c) $T(n) = T(n/3) + n$. (d) $T(n) = 2T(n/4) + \sqrt{n}$.

**Solution of Exercise 13.4.**

(a) $a = 4 > 2^1$: leaves, $\Theta(n^2)$. (b) $a = 4 = 2^2$: even, $\Theta(n^2 \log n)$. (c) $a = 1 < 3^1$: root, $\Theta(n)$. (d) $k = \frac12$ and $4^{1/2} = 2 = a$: even, $\Theta(\sqrt{n} \log n)$.

**Exercise 13.5 ★★.**

Find the error. “We prove $n^2 \in O(n)$ by induction on $n$. For $n = 1$, $1 \leq c \cdot 1$ with $c = 1$. If $n^2
\leq c n$, then $(n + 1)^2 = n^2 + 2n + 1 \leq cn + 3n = (c + 3)n \leq c'(n + 1)$ with $c' = c + 3$. So $n^2 \in O(n)$.”

**Solution of Exercise 13.5.**

The statement $n^2 \in O(n)$ asks for *one* constant $c$ valid for all large $n$. The “induction” proves $n^2 \leq
c_n n$ with a constant that grows at each step: $c_1 = 1$, $c_{n + 1} = c_n + 3$, so $c_n = 3n - 2$. What it proves is $n^2 \leq (3n - 2)n$, which is true and says nothing. An induction for a $O$ statement must keep the same constant in the hypothesis and the conclusion, and here it cannot: $n^2/n = n$ is unbounded.

**Exercise 13.6 ★★.**

A student reasons: “the inner loop runs at most $\log_2 n$ times, so the function [costs](#def-b1-asymptotic-analysis-cost) $\Theta(n \log n)$”. What is right and what is wrong? Find the true order, and prove it.

```python
def doublings(n):
    count = 0
    for i in range(1, n + 1):
        j = i
        while j < n:  # "at most log2 n times, so n log2 n in all"
            j *= 2
            count += 1
    return count
```

***Listing 13.5.** A loop that depends on $i$ code/bachelor-1/13-asymptotic-analysis/listings/exo_cost.py*

```
n=  1024  count=   2036  count/n=1.988  count/(n log2 n)=0.199
n=  8192  count=  16369  count/n=1.998  count/(n log2 n)=0.154
n= 65536  count= 131054  count/n=2.000  count/(n log2 n)=0.125
```

***Output 13.8.** The counts. Some lines are left out.*

**Solution of Exercise 13.6.**

The bound $O(n \log n)$ is right, but it is not a $\Theta$: the inner loop runs $\log_2 n$ times only for small $i$. For a given $i$ it runs $\lceil \log_2 (n/i) \rceil$ times, and at least $t$ times exactly when $i \cdot 2^{t - 1} < n$, for fewer than $n/2^{t - 1}$ values of $i$. Summing over $t \geq 1$, the count is below $n(1 + \frac12 + \frac14 + \cdots) =
2n$; and it is at least $n - 1$, since each $i < n$ runs once. So the [cost](#def-b1-asymptotic-analysis-cost) is $\Theta(n)$, and the output shows $\text{count}/n$ approaching 2 while $\text{count}/(n \log_2 n)$ tends to 0.

**Exercise 13.7 ★★.**

Write `count_triples(n)`, which counts the iterations of three nested loops over $0 \leq i < j < k < n$. Find a closed form, prove it, and test it against the counter.

**Solution of Exercise 13.7.**

```python
def count_triples(n):
    count = 0
    for i in range(n):
        for j in range(i + 1, n):
            for _k in range(j + 1, n):
                count += 1
    return count


def closed_form(n):
    return n * (n - 1) * (n - 2) // 6
```

*Three nested loops code/bachelor-1/13-asymptotic-analysis/exercises/nested_count.py*

Each iteration corresponds to one set $\{i, j, k\}$ of three distinct indices written in increasing order, and each such set to one iteration: there are $\binom{n}{3} = n(n - 1)(n - 2)/6$ of them, in $\Theta(n^3)$. The test compares the counter with the formula for $n < 12$.

**Exercise 13.8 ★★.**

Prove that $\sum_{i=1}^n i \log_2 i \in \Theta(n^2 \log n)$.

**Solution of Exercise 13.8.**

Upper bound: each term is at most $n \log_2 n$, so the sum is at most $n^2 \log_2 n$. Lower bound: the terms with $i
\geq n/2$, at least $n/2$ of them, are at least $\frac n2 \log_2 \frac n2$, so the sum is at least $\frac{n^2}{4}(\log_2 n
- 1) \geq \frac{n^2}{8} \log_2 n$ for $n \geq 4$.

**Exercise 13.9 ★★.**

Solve exactly $T(0) = 0$, $T(n) = T(n - 1) + n$, and $U(0) = 0$, $U(n) = 2U(n - 1) + 1$. Why does the master theorem not apply?

**Solution of Exercise 13.9.**

$T(n) = 1 + 2 + \dots + n = n(n + 1)/2$. For $U$, $U(n) + 1 = 2(U(n - 1) + 1)$, so $U(n) + 1 = 2^n$ and $U(n) = 2^n -
1$; both closed forms follow by induction, and the test checks them to $n = 59$. The master theorem covers subproblems of size $n/b$, a constant fraction of $n$; here the size decreases by 1, and the [recursion tree](#def-b1-asymptotic-analysis-recurrence) has $n$ levels instead of $\log_b n$.

**Exercise 13.10 ★★★.**

Prove the case $a = b^k$ of [Theorem 13.12](#thm-b1-asymptotic-analysis-master): give $T(n)$ exactly for $n = b^m$, and deduce $T(n) \in \Theta(n^k \log n)$.

**Solution of Exercise 13.10.**

With $q = a/b^k = 1$, the sum is $m = \log_b n$ and $a^m = n^{\log_b a} = n^k$, so $T(n) = n^k (T(1) + \log_b n)$ exactly. For $n \geq b$, $\log_b n \geq 1$, so $n^k \log_b n \leq T(n) \leq (T(1) + 1)\, n^k \log_b n$: $T(n) \in \Theta(n^k \log
n)$, the base of the logarithm being irrelevant.

**Exercise 13.11 ★★★.**

Let $T(1) = 0$ and $T(n) = T(\lfloor n/2 \rfloor) + T(\lceil n/2 \rceil) + n$ for $n \geq 2$. Prove that $T$ is increasing and that $T(n) \in \Theta(n \log n)$; then check that $T(n) = n\lceil \log_2 n \rceil + n - 2^{\lceil \log_2 n
\rceil}$ for every $n \geq 1$.

**Solution of Exercise 13.11.**

*Increasing*, by strong induction: $T(2) = 2 > T(1)$; for $n \geq 2$, $\lfloor (n + 1)/2 \rfloor \geq \lfloor n/2
\rfloor$ and $\lceil (n + 1)/2 \rceil \geq \lceil n/2 \rceil$, all four at most $n$, so by the hypothesis $T(n + 1) \geq
T(n) + 1$. *Order*: for $2^{m - 1} < n \leq 2^m$, $T(n) \leq T(2^m) = m 2^m \leq 2n(\log_2 n + 1)$ and $T(n) \geq
T(2^{m - 1}) = (m - 1)2^{m - 1} \geq \frac n2 (\log_2 n - 1)$, using the power-of-2 values $T(2^m) = m 2^m$ of [Output 13.4](#out-b1-asymptotic-analysis-recurrences). So $T(n) \in \Theta(n \log n)$. *Exact form*: the test checks $T(n)
= n\lceil \log_2 n \rceil + n - 2^{\lceil \log_2 n \rceil}$ for every $n < 3000$, and also $n \log_2 n \leq T(n) \leq n
\log_2 n + n$.

**Exercise 13.12 ★★★.**

Write `identify(a, b, k)`, which computes $T(b^i)$ for $T(n) = aT(n/b) + n^k$ and $T(1) = 1$, estimates the exponent of $T$ from the numbers, and says which case of the master theorem the numbers show, without using the comparison of $a$ with $b^k$. Test it against [Listing 13.2](#lst-b1-asymptotic-analysis-master).

**Solution of Exercise 13.12.**

```python
def values(a, b, k, levels):
    """T(b^0), ..., T(b^levels), with T(1) = 1."""
    t = [1]
    for i in range(1, levels + 1):
        t.append(a * t[-1] + b ** (i * k))
    return t


def identify(a, b, k, levels=40):
    """Estimates the exponent e of T from the last two values, and says which
    case of the master theorem the numbers show."""
    t = values(a, b, k, levels)
    e = log(t[-1] / t[-2], b)  # T(bn) / T(n) is about b^e
    if abs(e - k) > 0.05 and e > k:
        return "leaves", e
    # n^k times log n: T(n) / n^k grows by about one each level
    growth = t[-1] / b ** (levels * k) - t[-2] / b ** ((levels - 1) * k)
    return ("even" if growth > 0.5 else "root"), e
```

*Reading the case from the numbers code/bachelor-1/13-asymptotic-analysis/exercises/solve_rec.py*

The values $T(b^i)$ follow the recurrence directly, as integers. The ratio of the last two values is about $b^e$ for $T \in \Theta(n^e)$, and about $b^k(1 + 1/m)$ in the even case: an exponent clearly above $k$ means the leaves dominate. Otherwise the quotient $T(n)/n^k$ distinguishes the two other cases: it grows by about one per level in the even case (it is $T(1) + \log_b n$) and converges in the root case. The test compares the answer with [Listing 13.2](#lst-b1-asymptotic-analysis-master) on eleven recurrences.

## 13.8 Problem: Three ways to find a duplicate

**Problem 13.1.**

Weekend problem — Three ways to find a duplicate

The town’s library keeps its loans in order; which books were borrowed more than once among the first $n$ loans? Three functions answer, each counting its operations: one comparison of two loans, one comparison of neighbours after sorting, or one look-up in a set.

```python
def by_pairs(xs):
    ops, found = 0, set()
    for i in range(len(xs)):
        for j in range(i + 1, len(xs)):
            ops += 1  # one comparison
            if xs[i] == xs[j]:
                found.add(xs[i])
    return found, ops


def by_sorting(xs):
    counter = [0]
    s = merge_sort(xs, counter)
    found = set()
    for i in range(1, len(s)):
        counter[0] += 1  # one comparison of neighbours
        if s[i] == s[i - 1]:
            found.add(s[i])
    return found, counter[0]


def by_set(xs):
    ops, seen, found = 0, set(), set()
    for x in xs:
        ops += 1  # one look-up in seen, with its insertion
        if x in seen:
            found.add(x)
        seen.add(x)
    return found, ops
```

***Listing 13.6.** Three ways to find the duplicates code/bachelor-1/13-asymptotic-analysis/listings/duplicates.py*

```
$ python duplicates.py
  n dup  pairs sorting set   ratios
 25   5    300     112  25
 50  11   1225     275  50   4.08 2.46 2.00
100  29   4950     639 100   4.04 2.32 2.00
200  59  19900    1476 200   4.02 2.31 2.00
400  78  79800    3359 400   4.01 2.28 2.00
```

***Output 13.9.** The number of duplicated books, the counts, and their ratios as $n$ doubles.*

**Part I — The double loop.**

1. Show that `by_pairs` makes exactly $n(n - 1)/2$ comparisons, whatever the data.
2. Deduce that it is in $\Theta(n^2)$ , in the best, the worst and the average case.
3. Check the column `pairs` of the table.
4. Compute the ratio of the counts for $2n$ and $n$ , and its limit.
5. Could the function stop early? Rewrite its specification so that it can (“is there a duplicate?”), and give its best and worst cases then.
6. What is its [space cost](#def-b1-asymptotic-analysis-space) , beyond the input and the answer?

**Part II — Sort, then scan.**

7. Show that after sorting, two equal values are neighbours, and that the scan finds every duplicated value.
8. Merge sort makes at most $T(n)$ comparisons, with $T(1) = 0$ and $T(n) = T(\lfloor n/2 \rfloor) + T(\lceil n/2 \rceil) + n - 1$ . Show that $T(n) \leq n \lceil \log_2 n \rceil$ .
9. Deduce that `by_sorting` is in $O(n \log n)$ .
10. On the table, compare the counts with $n \log_2 n$ for $n = 400$ .
11. Show that $(2n)\log_2(2n) / (n \log_2 n) = 2(1 + 1/\log_2 n)$ , and compute it for $n = 25$ and $n = 200$ .
12. Why are the measured ratios not exactly these values?

**Part III — A set of seen values.**

13. Show that `by_set` makes exactly $n$ look-ups.
14. Under which assumption on the set is its [cost](#def-b1-asymptotic-analysis-cost) in $\Theta(n)$ ? (Hash tables are studied in [Chapter 16](https://one-course.com/books/computer-science/3/en/chapter/16-hash-tables#ch-b1-hash-tables) .)
15. What is the [space cost](#def-b1-asymptotic-analysis-space) of each of the three methods?
16. The book identifiers are numbers from 1 to 80. Give a method that uses a list of 80 booleans instead of a set, and its [cost](#def-b1-asymptotic-analysis-cost) .
17. For $n = 400$ , how many times fewer operations does the set make than the double loop?
18. Why does the table count only one operation per look-up, when a look-up does several [elementary operations](#def-b1-asymptotic-analysis-ram) ?

**Part IV — The doubling ratio.**

19. For a [cost](#def-b1-asymptotic-analysis-cost) $f(n) = c\,n^k$ , show that $f(2n)/f(n) = 2^k$ exactly.
20. For $f(n) = c\, n^k + d\,n^{k - 1}$ with $c > 0$ , show that the ratio tends to $2^k$ .
21. For $f \in \Theta(g)$ only, can the ratio of $f$ fail to converge? Give an example.
22. Read the ratios of the table, and say which order each column suggests.
23. Why do the ratios of the merge sort column approach 2 so slowly?
24. State the named result of the problem, *the doubling ratio test* : the limits of the ratios for counts $c\,n^2$ , $c\,n \log_2 n$ and $c\,n$ , proved, and the values read from the table.

**Solution of Problem 13.1.**

**1.** For each $i$ the inner loop runs $n - 1 - i$ times: $(n - 1) + (n - 2) + \dots + 0 = n(n - 1)/2$, independent of the values.

**2.** Every input of size $n$ [costs](#def-b1-asymptotic-analysis-cost) the same, so the three cases coincide, in $\Theta(n^2)$.

**3.** $25 \cdot 24/2 = 300$, $1225$, $4950$, $19\,900$ and $400 \cdot 399/2 = 79\,800$.

**4.** $\frac{2n(2n - 1)}{n(n - 1)} = \frac{2(2n - 1)}{n - 1} \to 4$; for $n = 25$ it is $1225/300 \approx 4.08$.

**5.** Return as soon as two equal values are found. Best case: the first two loans are of the same book, one comparison; worst case: no duplicate, $n(n - 1)/2$ comparisons.

**6.** $\Theta(1)$: two indices and a counter.

**7.** In a sorted list the occurrences of a value form one block of consecutive positions; a value occurring at least twice has two neighbours in its block, which the scan compares.

**8.** By strong induction, with $c = \lceil \log_2 n \rceil$: since $n \leq 2^c$, both halves have at most $2^{c - 1}$ elements, so $T(n) \leq \lfloor \frac n2 \rfloor (c - 1) + \lceil \frac n2 \rceil (c - 1) + n - 1 < nc$.

**9.** At most $n \lceil \log_2 n \rceil$ comparisons to sort and $n - 1$ to scan: $O(n \log n)$.

**10.** $400 \log_2 400 \approx 3458$; the count is 3359, of which 399 for the scan: merge sort used about 2960, below the bound, because a merge stops comparing when one half is exhausted.

**11.** $\frac{2n \log_2 (2n)}{n \log_2 n} = \frac{2(\log_2 n + 1)}{\log_2 n}$. For $n = 25$: $2(1 + 1/4.64) \approx
2.43$; for $n = 200$: $2(1 + 1/7.64) \approx 2.26$. The table shows 2.46 and 2.28.

**12.** The counts are not exactly $c\,n \log_2 n$: the merges depend on the data, and the scan adds a linear term.

**13.** One look-up per element of the list: $n$.

**14.** That a look-up and an insertion each [cost](#def-b1-asymptotic-analysis-cost) a bounded number of [elementary operations](#def-b1-asymptotic-analysis-ram), which hash tables achieve on average.

**15.** The double loop $\Theta(1)$; sorting $\Theta(n)$, for the copies made by merge sort; the set as many cells as there are distinct values, at most $n$ (here at most 80).

**16.** `seen = [False] * 81`; for each `x`, test and set `seen[x]`: $n$ steps of constant [cost](#def-b1-asymptotic-analysis-cost), plus 81 to create the list, $\Theta(n)$ time and $\Theta(1)$ space for a fixed range of identifiers.

**17.** $79\,800/400 \approx 200$ times fewer.

**18.** The model counts one dominant operation; each look-up [costs](#def-b1-asymptotic-analysis-cost) a bounded number of [elementary operations](#def-b1-asymptotic-analysis-ram), so the true [cost](#def-b1-asymptotic-analysis-cost) is within a constant factor of the count, which $\Theta$ ignores.

**19.** $c(2n)^k/(c\,n^k) = 2^k$.

**20.** Dividing numerator and denominator by $n^k$: $\frac{c\,2^k + d\,2^{k - 1}/n}{c + d/n} \to 2^k$.

**21.** Yes. $f(n) = n$ when $\lfloor \log_2 n \rfloor$ is even and $3n$ when it is odd is in $\Theta(n)$, but $f(2n)/f(n)$ alternates between 6 and $2/3$.

**22.** `pairs`: 4.08, 4.04, 4.02, 4.01, quadratic; `sorting`: 2.46, 2.32, 2.31, 2.28, slightly above 2 and decreasing, $n \log n$; `set`: exactly 2.00, linear.

**23.** The excess $2/\log_2 n$ decreases like a logarithm: it is still 0.2 at $n = 1024$ and 0.1 at about a million.

**24.** *The doubling ratio test*: when $n$ doubles, the ratio of the counts tends to 4 for $c\,n^2$ (question 19), to 2 for $c\,n$, and equals $2(1 + 1/\log_2 n)$ for $c\,n \log_2 n$ (question 11), which tends to 2 from above. On the table the double loop gives 4.08 down to 4.01, sorting 2.46 down to 2.28, and the set 2.00: $\Theta(n^2)$, $\Theta(n
\log n)$ and $\Theta(n)$. The test is a diagnosis, not a proof: question 21 shows a $\Theta(n)$ [cost](#def-b1-asymptotic-analysis-cost) whose ratio never settles.
