---
title: "Time and Space Complexity"
book: "University Computer Science — Year 3"
subject: computer-science
language: en
chapter: 16
exercises: 12
source: https://one-course.com/books/computer-science/5/en/chapter/16-time-and-space-complexity
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 16 — Time and Space Complexity

[Chapter 15](https://one-course.com/books/computer-science/5/en/chapter/15-turing-machines-and-computability#ch-b3-computability) separated the problems that have a program from those that have none. Among the problems that do, some are solved in a fraction of a second on inputs of millions of items and others take longer than any computer can run once the input has a hundred. This chapter measures problems, not programs: it groups them into classes by the time or the space the best machine needs, and asks how the classes relate. Checking a proposed answer turns out to be easy for many problems whose search looks hard, which defines NP; a search can be built from a yes-or-no oracle; more time and more space provably give more power; and space behaves better than time: a nondeterministic search through a maze can be replaced by a deterministic one using only the square of its memory.

**You already know.**

$f = O(g)$ means $f(n) \le c\,g(n)$ for some constant $c$ and all large $n$; a polynomial bound is $O(n^c)$ for a constant $c$ (Year 1 volume). [Chapter 15](https://one-course.com/books/computer-science/5/en/chapter/15-turing-machines-and-computability#ch-b3-computability) defined [Turing machines](https://one-course.com/books/computer-science/5/en/chapter/15-turing-machines-and-computability#def-b3-computability-tm) with one or several tapes, and showed that one tape simulates $k$ with a quadratic slowdown. Backtracking explores the choices of a search one at a time, undoing each choice that leads nowhere, and may try exponentially many (Year 1 volume).

## 16.1 Classes of time and space

**Definition 16.1 (Decision problem, instance size).**

A *decision problem* is a set of instances, each with the answer yes or no; formally, the language of the encodings of the yes-instances. The *instance size* $n$ is the length of the encoding: a list of numbers takes the total number of their digits, a graph its number of vertices and edges, up to a constant factor.

The encoding matters only in one way: numbers must be written in a base of at least 2. Written in unary, the number $N$ takes $N$ symbols instead of about $\log_2 N$, and an algorithm that takes $N$ steps would look linear when it is exponential in the length of $N$.

**Definition 16.2 (Time complexity class, space complexity class, class P).**

For a function $f$, the *time complexity class* $\mathrm{TIME}(f)$ is the set of [decision problems](#def-b3-complexity-classes-decision) decided by a [multi-tape Turing machine](https://one-course.com/books/computer-science/5/en/chapter/15-turing-machines-and-computability#def-b3-computability-multitape) in $O(f(n))$ steps on inputs of size $n$. The *space complexity class* $\mathrm{SPACE}(f)$ is the set decided using $O(f(n))$ cells of work tapes, the input being on a read-only tape that does not count. The *class P* is $\bigcup_c \mathrm{TIME}(n^c)$: the problems [decidable](https://one-course.com/books/computer-science/5/en/chapter/15-turing-machines-and-computability#def-b3-computability-languages) in polynomial time.

P is robust: one tape simulates several with a quadratic slowdown ([Theorem 15.4](https://one-course.com/books/computer-science/5/en/chapter/15-turing-machines-and-computability#thm-b3-computability-multitape)), and a random-access machine, or a Python program whose integers stay of polynomial size, is simulated by a [Turing machine](https://one-course.com/books/computer-science/5/en/chapter/15-turing-machines-and-computability#def-b3-computability-tm) with a polynomial slowdown too. So whether a problem is in P does not depend on the model, while whether it is in $\mathrm{TIME}(n^2)$ does. Cobham and Edmonds proposed in 1965 to take P as the formal meaning of “feasibly computable”.

The time and space classes go back to Hartmanis and Stearns, and to Stearns, Hartmanis and Lewis, both in 1965.

## 16.2 P and NP

To decide whether some of the numbers $3, 34, 4, 12, 5, 2$ add up to $9$, a search may try all 64 subsets. To be convinced that they do, it is enough to be shown $\{4, 5\}$ and to add. Many problems share that shape: finding is hard, checking is easy.

**Definition 16.3 (Certificate, verifier, class NP, nondeterministic Turing machine).**

A *verifier* for a [decision problem](#def-b3-complexity-classes-decision) $A$ is an algorithm $V$ that takes an instance $x$ and a word $c$, the *certificate*, such that $x$ is a yes-instance if and only if $V(x, c)$ accepts for some $c$. The *class NP* is the set of problems that have a verifier running in time polynomial in the size of $x$ (so only certificates of polynomial length matter). A *nondeterministic Turing machine* may have several transitions for the same state and symbol; it accepts when some sequence of choices leads to acceptance.

NP stands for “nondeterministic polynomial time”: a problem has a polynomial-time [verifier](#def-b3-complexity-classes-np) if and only if a nondeterministic machine decides it in polynomial time, since the machine can guess the [certificate](#def-b3-complexity-classes-np) one symbol per step, and conversely its choices form a [certificate](#def-b3-complexity-classes-np). P is contained in NP: a problem decided in polynomial time has the [verifier](#def-b3-complexity-classes-np) that ignores the [certificate](#def-b3-complexity-classes-np). Whether the inclusion is strict is the question of [Chapter 17](https://one-course.com/books/computer-science/5/en/chapter/17-np-completeness#ch-b3-np-completeness).

`verifiers.py` checks [certificates](#def-b3-complexity-classes-np) for subset sum (a set of indices), Hamiltonian path (an ordering of the vertices, each consecutive pair joined by an edge) and 3-colouring (a colour per vertex, different at the ends of each edge), and counts its steps.

```python
def hamiltonian_path(n, edges, order):
    """Certificate: the vertices 0..n-1, each once, consecutive ones adjacent."""
    steps, adjacent = len(edges), set(edges) | {(v, u) for u, v in edges}
    if sorted(order) != list(range(n)):
        return False, steps + n
    for u, v in zip(order, order[1:]):
        steps += 1
        if (u, v) not in adjacent:
            return False, steps
    return True, steps


def three_colouring(n, edges, colour):
    """Certificate: a colour 0, 1 or 2 per vertex, the ends of each edge different."""
    steps = n
    if len(colour) != n or any(c not in (0, 1, 2) for c in colour):
        return False, steps
    for u, v in edges:
        steps += 1
        if colour[u] == colour[v]:
            return False, steps
    return True, steps
```

***Listing 16.1.** Two of the three [verifiers](#def-b3-complexity-classes-np). Each looks at every vertex and edge once. code/bachelor-3/16-complexity-classes/listings/verifiers.py*

```
$ python verifiers.py
    n   subset sum   Hamiltonian path   3-colouring   (steps, all accepted)
   10            5                 29            30
  100           50                299           300
 1000          500               2999          3000
10000         5000              29999         30000
```

***Output 16.1.** Verification steps on graphs with $n$ vertices and $2n$ edges: linear in $n$.*

Without a [certificate](#def-b3-complexity-classes-np), the obvious algorithm for subset sum tries every subset. The program `search_vs_verify.py` builds all $2^n$ subset sums of $n$ even numbers, looking for an odd target that is never there; checking a [certificate](#def-b3-complexity-classes-np) would take $n$ steps.

![Searching against checking, for subset sum with no solution, on a logarithmic scale: from search_vs_verify.py. At n = 22 the search computes 4,194,304 sums.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-complexity-classes/fig-6fb3eb0a1126.svg)

*Searching against checking, for subset sum with no solution, on a logarithmic scale: from `search_vs_verify.py`. At $n = 22$ the search computes 4,194,304 sums.*

An optimisation problem becomes a [decision problem](#def-b3-complexity-classes-decision) with a threshold: “what is the shortest tour?” becomes “is there a tour of length at most $B$?”. If the decision is easy, so is the optimum, by binary search on $B$ ([Exercise 16.2](#exo-b3-complexity-classes-2)). The search for a solution, not only its value, also reduces to decisions.

**Definition 16.4 (Self-reducibility).**

A problem in NP is *self-reducible* when a [certificate](#def-b3-complexity-classes-np) for a yes-instance can be found in polynomial time with the help of an oracle that answers the [decision problem](#def-b3-complexity-classes-decision) itself, each call counting as one step.

**Theorem 16.5 (SAT is self-reducible).**

Given an oracle that decides whether a Boolean formula in conjunctive normal form is satisfiable, a satisfying assignment of a satisfiable formula with $n$ variables can be found with $n + 1$ calls.

**Proof.** One call checks that $\varphi$ is satisfiable. Then, for $i = 1, \ldots, n$: let $\varphi_1$ be $\varphi$ with $x_i$ set to true and simplified. If the oracle says $\varphi_1$ is satisfiable, keep $x_i =$ true and continue with $\varphi_1$. Otherwise every satisfying assignment of $\varphi$, and there is one by the invariant “the current formula is satisfiable”, has $x_i =$ false, so continue with $\varphi$ with $x_i$ set to false, without asking. The invariant holds at every step, and after $n$ steps all variables are set and the formula is satisfied. ∎

```python
def fix(clauses, i, value):
    """Set x_i: drop the satisfied clauses, remove the literal from the others. An
    emptied clause stays, as an empty clause, which no assignment satisfies."""
    lit = i if value else -i
    return [[x for x in c if x != -lit] for c in clauses if lit not in c]


def find_assignment(clauses, n):
    if not satisfiable(clauses, n):
        return None
    values = []
    for i in range(1, n + 1):
        trial = fix(clauses, i, True)
        if satisfiable(trial, n):  # keep x_i = True if the rest can still be satisfied
            clauses, value = trial, True
        else:  # otherwise x_i = False must work, since the formula was satisfiable
            clauses, value = fix(clauses, i, False), False
        values.append(value)
    return values
```

***Listing 16.2.** Finding an assignment with a yes-or-no oracle: one call per variable, plus one. code/bachelor-3/16-complexity-classes/listings/self_reduce.py*

```
$ python self_reduce.py
n =  6, 24 clauses: satisfiable, 7 oracle calls, assignment checked: True
n =  8, 32 clauses: satisfiable, 9 oracle calls, assignment checked: True
n = 10, 40 clauses: satisfiable, 11 oracle calls, assignment checked: True
n = 12, 48 clauses: satisfiable, 13 oracle calls, assignment checked: True
n =  3, 8 clauses: None, 1 oracle call
```

***Output 16.2.** $n + 1$ oracle calls when the formula is satisfiable, one when it is not.*

The oracle here is an exhaustive search, but the algorithm uses only its answers: whatever the oracle costs, finding costs at most $n + 1$ times as much as deciding.

## 16.3 The hierarchy theorems

More time should give more power. Hartmanis and Stearns proved it, by diagonalisation.

**Theorem 16.6 (Time hierarchy theorem, space hierarchy theorem).**

For a function $f$ computable in time $f$ itself, some problem is decided in time $O(f(n) \log f(n))$ but not in time $o(f(n))$. For a function $f \ge \log n$ computable in space $f$, some problem is decided in space $O(f(n))$ but not in space $o(f(n))$.

**Proof idea.** The machine $D$, on input $\langle M \rangle$ padded with symbols, simulates $M$ on its own input for $f(n)$ steps and does the opposite of what $M$ answers. No machine $M$ running in time $o(f)$ decides the same problem as $D$: on long enough paddings of $\langle M \rangle$ the simulation finishes and $D$ disagrees with $M$. The factor $\log f(n)$ pays for the simulation’s step counter and for moving $M$’s description along the tapes; the space version needs no such factor. ∎

So $\mathrm{TIME}(n^a)$ is strictly smaller than $\mathrm{TIME}(n^b)$ when $a < b$, and P is strictly smaller than [EXP](#def-b3-complexity-classes-pspace), the class defined in [Section 16.4](#sec-16-4) ([Exercise 16.11](#exo-b3-complexity-classes-11)).

The theorems separate classes of the same kind, time from time and space from space. They say nothing about P against NP, whose machines differ in kind.

## 16.4 Polynomial space

**Definition 16.7 (EXP, PSPACE, TQBF).**

*EXP* is $\bigcup_c \mathrm{TIME}(2^{n^c})$ and *PSPACE* is $\bigcup_c \mathrm{SPACE}(n^c)$; NPSPACE is the same with nondeterministic machines. *TQBF* is the problem of deciding whether a fully quantified Boolean formula $Q_1 x_1\, Q_2 x_2 \cdots Q_n x_n\, \varphi$, each $Q_i$ being $\exists$ or $\forall$, is true.

Space can be reused and time cannot, so space is the more generous resource: a machine that runs for $t$ steps uses at most $t$ cells, and a machine that uses $s$ cells has at most $2^{O(s)}$ configurations, so if it halts it does within that many steps. Hence $\mathrm{P} \subseteq \mathrm{PSPACE} \subseteq \mathrm{EXP}$, and NP is inside [PSPACE](#def-b3-complexity-classes-pspace) too ([Exercise 16.8](#exo-b3-complexity-classes-8)).

[TQBF](#def-b3-complexity-classes-pspace) is a game. $\exists x_1\, \forall x_2\, \exists x_3 \ldots \varphi$ says: the first player can choose $x_1$ so that whatever the second chooses for $x_2$, the first can choose $x_3$ so that …, and in the end $\varphi$ holds. A recursion evaluates it in space proportional to $n$, keeping only one branch at a time: the depth is $n$, the time $2^n$.

```python
def value(quantifiers, phi, bits=()):
    """Evaluate Q1 x1 Q2 x2 ... phi(x): depth n, one branch stored at a time."""
    global calls
    calls += 1
    if len(bits) == len(quantifiers):
        return phi(bits)
    branches = (value(quantifiers, phi, bits + (b,)) for b in (False, True))
    return any(branches) if quantifiers[len(bits)] == "E" else all(branches)
```

***Listing 16.3.** Evaluating a quantified formula by recursion: `any` for $\exists$, `all` for $\forall$. code/bachelor-3/16-complexity-classes/listings/qbf.py*

```
$ python qbf.py
 1 tokens: E            first player wins;     2 calls, depth 1
 2 tokens: EA           first player wins;     6 calls, depth 2
 3 tokens: EAE          second player wins;    11 calls, depth 3
 4 tokens: EAEA         first player wins;    12 calls, depth 4
 5 tokens: EAEAE        first player wins;    30 calls, depth 5
 6 tokens: EAEAEA       second player wins;    49 calls, depth 6
 7 tokens: EAEAEAE      first player wins;    50 calls, depth 7
 8 tokens: EAEAEAEA     first player wins;   126 calls, depth 8
 9 tokens: EAEAEAEAE    second player wins;   203 calls, depth 9
10 tokens: EAEAEAEAEA   first player wins;   204 calls, depth 10
11 tokens: EAEAEAEAEAE  first player wins;   502 calls, depth 11
12 tokens: EAEAEAEAEAEA second player wins;   801 calls, depth 12
```

***Output 16.3.** The game “take 1 or 2 tokens, whoever takes the last wins”: the second player wins exactly when $m$ is a multiple of 3.*

[TQBF](#def-b3-complexity-classes-pspace) is in [PSPACE](#def-b3-complexity-classes-pspace), and every problem in [PSPACE](#def-b3-complexity-classes-pspace) reduces to it in polynomial time: it is complete for [PSPACE](#def-b3-complexity-classes-pspace), as Stockmeyer and Meyer showed in 1973.

### 16.4.1 Savitch’s theorem

Nondeterminism seems to buy exponential time; for space it buys at most a square. The key is reachability: is there a path from $u$ to $v$ in a graph of $n$ vertices? A nondeterministic machine walks, guessing each next vertex and remembering only the current one and a step counter: $O(\log n)$ bits. Breadth-first search is deterministic but stores a set of up to $n$ visited vertices. Savitch’s algorithm stores neither.

**Theorem 16.8 (Savitch’s theorem).**

Reachability in a directed graph of $n$ vertices can be decided deterministically in space $O(\log^2 n)$. More generally, every problem decided by a nondeterministic machine in space $f(n) \ge \log n$ is decided by a deterministic machine in space $O(f(n)^2)$; in particular NPSPACE $=$ [PSPACE](#def-b3-complexity-classes-pspace).

**Proof.** Let $R(u, v, k)$ say that a path of length at most $2^k$ leads from $u$ to $v$. $R(u, v, 0)$ holds when $u = v$ or $(u, v)$ is an edge. For $k > 0$, $R(u, v, k)$ holds if and only if there is a vertex $w$ with $R(u, w, k - 1)$ and $R(w, v, k - 1)$: cut the path in its middle. Compute $R$ by this recursion, trying $w = 1, \ldots, n$ and evaluating the two halves one after the other. A frame stores $u$, $v$, $k$ and $w$, $O(\log n)$ bits, and the recursion is $k + 1$ frames deep. Paths need at most $n - 1$ edges, so $k = \lceil \log_2 n \rceil$ suffices: $O(\log n)$ frames of $O(\log n)$ bits. The general statement applies the same recursion to the graph of configurations of the nondeterministic machine, which has $2^{O(f(n))}$ vertices, each written in $O(f(n))$ bits ([Exercise 16.10](#exo-b3-complexity-classes-10)). ∎

Walter Savitch published it in 1970.

![Savitch’s recursion for paths of length at most 8: each node tries every midpoint, but only the current chain of calls from the root is in memory. The calls with k = 0, which only test for an edge, are not drawn.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-complexity-classes/fig-5ec2996824e8.svg)

*Savitch’s recursion for paths of length at most 8: each node tries every midpoint, but only the current chain of calls from the root is in memory. The calls with $k = 0$, which only test for an edge, are not drawn.*

```python
    def reach(self, u, v, k):
        self.calls += 1
        self.depth += 1
        self.max_depth = max(self.max_depth, self.depth)
        if k == 0:
            found = u == v or (u, v) in self.edges
        else:
            found = any(self.reach(u, w, k - 1) and self.reach(w, v, k - 1)
                        for w in range(self.n))
        self.depth -= 1
        return found

    def path_exists(self, u, v):
        return self.reach(u, v, max(1, math.ceil(math.log2(self.n))))
```

***Listing 16.4.** The midpoint recursion, with its calls and its depth counted. code/bachelor-3/16-complexity-classes/listings/savitch.py*

```
$ python savitch.py
directed path 0 -> 1 -> ... -> n-1; from 0 to n-1, then back from n-1 to 0
  n   k   reachable  depth        calls   unreachable  depth        calls
  2   1        True      2            3         False      2            4
  4   2        True      3           20         False      3           31
  8   3        True      4          443         False      4          820
 16   4        True      5       47,038         False      5       88,741
town: 30 places, 53 roads (1 one-way), 105 directed edges
place 1 to place 30: True, depth 6, 1,858 calls; BFS visits 30 places
```

***Output 16.4.** The depth is $k + 1$; the calls grow like $n^{\log_2 n}$. On the town’s road map BFS visits all 30 places.*

The memory is tiny and the time is not: on 16 vertices the unreachable query makes 88,741 calls, about $2^{16} = 16^{\log_2 16}$. Savitch’s algorithm is a statement about space, not a way to find a route; the weekend problem measures the trade-off.

## 16.5 Logarithmic space

**Definition 16.9 (Class L, class NL, log-space reduction).**

The *class L* is $\mathrm{SPACE}(\log n)$: a deterministic machine with a read-only input and a work tape of $O(\log n)$ cells, enough for a constant number of counters and pointers into the input. The *class NL* is the same for nondeterministic machines. A *log-space reduction* is a [many-one reduction](https://one-course.com/books/computer-science/5/en/chapter/15-turing-machines-and-computability#def-b3-computability-reduction) computed by such a machine with a write-only output tape.

Reachability is in NL, by the guessing walk, and every problem in NL reduces to it in logarithmic space: it is complete for NL. Savitch’s theorem puts NL inside $\mathrm{SPACE}(\log^2 n)$. The complement, “is there no path?”, seems to need a [certificate](#def-b3-complexity-classes-np) as long as the whole set of reachable vertices, yet Immerman and Szelepcsényi showed independently in 1987 that it is in NL too: NL is closed under complement.

The known inclusions form a chain.

![L ⊂eq NL ⊂eq P ⊂eq NP ⊂eq PSPACE ⊂eq EXP. The hierarchy theorems make NL PSPACE and P EXP; every other inclusion drawn might be an equality.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-complexity-classes/fig-82d75d935028.svg)

*$\mathrm{L} \subseteq \mathrm{NL} \subseteq \mathrm{P} \subseteq \mathrm{NP} \subseteq \mathrm{PSPACE} \subseteq \mathrm{EXP}$. The hierarchy theorems make $\mathrm{NL} \ne \mathrm{PSPACE}$ and $\mathrm{P} \ne \mathrm{EXP}$; every other inclusion drawn might be an equality.*

## 16.6 Exercises

**Exercise 16.1 ★.**

For each problem, say what a [certificate](#def-b3-complexity-classes-np) is and how to check it in polynomial time: (a) the number $N$ is composite; (b) the graph has a cycle through every vertex; (c) the graph has $k$ vertices that are pairwise adjacent; (d) a partly filled grid of a puzzle can be completed by the rules.

**Solution of Exercise 16.1.**

(a) A factor $d$ with $1 < d < N$: one division, polynomial in the number of digits of $N$. (b) The cycle, as an order of the vertices: check that each vertex appears once and that consecutive vertices, the last and the first included, are adjacent. (c) The $k$ vertices: check that they are distinct and that each of the $k(k - 1)/2$ pairs is an edge. (d) The completed grid: check that it extends the given entries and obeys every rule, each rule looking at a few cells.

**Exercise 16.2 ★.**

The optimisation problem: given distances between $n$ towns, the length of the shortest tour visiting each once. Write the decision version with a threshold, and show that a polynomial-time algorithm for the decision version gives one for the optimum when distances are integers below $2^{32}$.

**Solution of Exercise 16.2.**

Decision version: given the distances and a number $B$, is there a tour of length at most $B$? A tour has $n$ legs below $2^{32}$, so its length lies in $[0, n \cdot 2^{32}]$. Binary search on $B$ over that interval finds the least $B$ with a yes answer, which is the optimum, in about $32 + \log_2 n$ calls; each call is polynomial, and so is the total.

**Exercise 16.3 ★.**

How much work space, in bits, do these use on a list of $n$ numbers of at most $b$ bits? (a) Computing the maximum in one pass. (b) Checking that the list is sorted. (c) Sorting a copy. (d) Breadth-first search on a graph of $n$ vertices.

**Solution of Exercise 16.3.**

(a) $O(b + \log n)$ bits: the current maximum and an index. (b) The same: the previous number and an index. (c) $O(nb)$ bits for the copy. (d) $O(n \log n)$ bits: a queue of up to $n$ vertex numbers and $n$ bits for the visited set.

**Exercise 16.4 ★.**

Predict the number of oracle calls of `find_assignment` on a satisfiable formula with 20 variables, on an unsatisfiable one, and on a satisfiable one in which every variable must be false.

**Solution of Exercise 16.4.**

21, 1 and 21. `find_assignment` asks once at the start, then once per variable whatever the answer; when every variable must be false, each of the 20 trials answers no and the second branch is taken without a call (`test_self_reduction_uses_n_plus_one_calls_and_exercise_4`).

**Exercise 16.5 ★★.**

`exercises/ex5_hampath.py` has a Hamiltonian-path [verifier](#def-b3-complexity-classes-np) that accepts the [certificate](#def-b3-complexity-classes-np) 0, 1, 0, 1 on the path $0 - 1 - 2 - 3$. Explain why and fix it.

**Solution of Exercise 16.5.**

The buggy [verifier](#def-b3-complexity-classes-np) checks only that the [certificate](#def-b3-complexity-classes-np) has $n$ entries and that consecutive entries are adjacent: 0, 1, 0, 1 has four entries and uses the edge $0 - 1$ three times, but never visits 2 or 3. The fix requires the [certificate](#def-b3-complexity-classes-np) to be a permutation of $0, \ldots, n - 1$, `sorted(order) == list(range(n))`, as `hamiltonian_path` does.

**Exercise 16.6 ★★.**

Write `verify_clique(n, edges, k, chosen)`, a [verifier](#def-b3-complexity-classes-np) for “the graph has a clique of $k$ vertices” running in $O(m + k^2)$ steps. It is tested against brute force on every small graph.

**Solution of Exercise 16.6.**

`exercises/ex6_clique.py`: reject unless `chosen` has $k$ distinct vertices of the graph; put both directions of every edge in a set, $O(m)$; then look up each of the $k(k - 1)/2$ pairs, $O(k^2)$. The test is `test_exercise_6_clique`.

**Exercise 16.7 ★★.**

Prove that 3-colouring is [self-reducible](#def-b3-complexity-classes-self-reducibility): given an oracle for “is this graph 3-colourable?”, find a colouring with a polynomial number of calls. (Try joining two vertices by an edge, or merging them.)

**Solution of Exercise 16.7.**

Facts used: adding edges never makes a non-colourable graph colourable; a vertex adjacent to two vertices of a triangle must take the third one’s colour.

Add a triangle $t_0, t_1, t_2$ to $G$; the new graph is 3-colourable exactly when $G$ is, and in any colouring the triangle uses all three colours. For each vertex $v$ in turn, and for $c = 0, 1$: join $v$ to the two triangle vertices other than $t_c$, and ask the oracle; if it says yes, keep the edges and go to the next vertex, otherwise remove them. If neither $c = 0$ nor $c = 1$ works, join $v$ to $t_0$ and $t_1$ without asking: since the graph was colourable before, some colouring gives $v$ one of the three triangle colours, and it was not that of $t_0$ or $t_1$. The invariant “the current graph is 3-colourable” holds throughout, at most $2n + 1$ calls are made, and at the end each $v$ is forced to the colour of one triangle vertex: reading these gives a 3-colouring of $G$.

**Exercise 16.8 ★★.**

Prove $\mathrm{NP} \subseteq \mathrm{PSPACE}$.

**Solution of Exercise 16.8.**

Let $V$ be a [verifier](#def-b3-complexity-classes-np) for $A$ running in time $p(n)$; it reads at most $p(n)$ symbols of the [certificate](#def-b3-complexity-classes-np). On $x$, enumerate the [certificates](#def-b3-complexity-classes-np) of length at most $p(n)$ one after the other, in one buffer of $p(n)$ cells, run $V(x, c)$ on each, reusing its space, and accept if one is accepted. The space is $O(p(n))$ for the buffer plus $O(p(n))$ for a run of $V$, which cannot use more cells than steps: polynomial. The time is exponential, which does not matter.

**Exercise 16.9 ★★.**

Bound the number of calls of `reach(u, v, k)` on a graph of $n$ vertices, and compare with [Output 16.4](#out-b3-complexity-classes-savitch). Why does the reachable query make fewer calls than the unreachable one?

**Solution of Exercise 16.9.**

A call with $k > 0$ makes at most $2n$ calls with $k - 1$, two per midpoint, so $C(k) \le 1 + 2n\,C(k - 1)$ with $C(0) = 1$, and $C(k) \le (2n + 1)^k$. For $n = 16$, $k = 4$: $33^4 = 1{,}185{,}921$, against 88,741 printed for the unreachable query. The reachable query stops at the first midpoint that works, since `any` stops at the first true; and on either query `and` skips the second half when the first is false. On the unreachable query no midpoint works, so every midpoint is tried at every level.

**Exercise 16.10 ★★★.**

Complete the proof of Savitch’s theorem: a nondeterministic machine using space $f(n) \ge \log n$ is simulated deterministically in space $O(f(n)^2)$. Say what the vertices and edges of the configuration graph are, how many there are, and how the simulation reads an edge without storing the graph.

**Solution of Exercise 16.10.**

Facts used: the input is on a read-only tape and does not count; $f(n) \ge \log n$.

A configuration of the machine on $x$ is its state, the position of the input head ($O(\log n)$ bits), the position of the work head ($O(\log f(n))$ bits) and the work tape ($O(f(n))$ symbols): $O(f(n))$ bits, so there are $N = 2^{O(f(n))}$ configurations. The configuration graph has an edge $c \to c'$ when one step leads from $c$ to $c'$; whether it does is decided by looking at the transition table and at the input symbol under $c$’s input head, in space $O(f(n))$, without storing the graph. Make the machine erase its tape and move its heads home before accepting, so that there is one accepting configuration $c_{\mathrm{acc}}$. The machine accepts $x$ if and only if $c_{\mathrm{acc}}$ is reachable from the start configuration, and Savitch’s recursion with $k = \lceil \log_2 N \rceil = O(f(n))$ decides it with $k + 1$ frames of $O(f(n))$ bits: $O(f(n)^2)$. Computing $k$ requires $f$ to be computable in space $f$, or trying $k = 1, 2, \ldots$ in turn.

**Exercise 16.11 ★★★.**

Prove $\mathrm{P} \ne \mathrm{EXP}$ from the time hierarchy theorem.

**Solution of Exercise 16.11.**

Take $f(n) = 2^n$. The time hierarchy theorem gives a problem $A$ decided in time $O(2^n \cdot n)$, so $A \in \mathrm{TIME}(2^{n^2}) \subseteq \mathrm{EXP}$, but in no time $o(2^n)$. Every problem in P is in $\mathrm{TIME}(n^c)$ for some $c$, and $n^c = o(2^n)$. So $A$ is not in P: $\mathrm{P} \ne \mathrm{EXP}$.

**Exercise 16.12 ★★★.**

A graph is 2-colourable if and only if it has no cycle of odd length. Write `two_colourable(n, edges)` that stores no list or set, only a few vertex numbers per recursive call, by running Savitch’s recursion on the graph whose vertices are pairs (vertex, parity of the walk so far). What space does it use? It is tested against breadth-first colouring on random graphs.

**Solution of Exercise 16.12.**

`exercises/ex12_bipartite.py`. A walk from $v$ back to $v$ of odd length exists if and only if the graph has an odd cycle, since an odd closed walk contains an odd cycle; so the graph is 2-colourable if and only if no $(v, 0)$ reaches $(v, 1)$ in the parity graph. That graph has $2n$ vertices, and an edge $(x, p) \to (y, 1 - p)$ for each edge $xy$; the function `adjacent` reads it from the edge set without building it. The recursion is $\lceil \log_2 2n \rceil + 1$ frames deep, each holding six small numbers, $O(\log n)$ bits: $O(\log^2 n)$ space, the input aside (`test_exercise_12_bipartite`).

## 16.7 Weekend problem

**Problem 16.1.**

Weekend problem — Savitch in the maze

Brenmoor’s road map has 30 places and 53 roads, one of them one-way. This problem compares two ways of deciding whether one place can be reached from another: breadth-first search, fast but with a memory that grows with the map, and Savitch’s recursion, which remembers almost nothing and pays for it in time. The counts are those of [Output 16.4](#out-b3-complexity-classes-savitch).

**Part I — Breadth-first search.**

1. How many steps does BFS take on a graph of $n$ vertices and $m$ edges? Count them for the town, with each two-way road as two directed edges.
2. How much memory does BFS use, in vertices and in bits, when every place is reachable?
3. Why can BFS not do with less, when it must remember which places it has seen?
4. Depth-first search uses a stack instead of a queue. Is its memory smaller in the worst case?
5. With $n = 10^9$ vertices, how much memory does BFS need, at 4 bytes per vertex?

**Part II — The midpoint recursion.**

6. What $k$ does `path_exists` use for the town, and why is it enough?
7. What does one frame store, and how many bits does it need for 30 places?
8. Check the printed depth for the town against $k + 1$ .
9. Bound the total memory in bits, and compare with BFS.
10. For $n = 10^9$ , how many frames and how many bytes does the recursion need?
11. Why does the recursion evaluate the two halves one after the other rather than both at once?

**Part III — What it costs.**

12. Write a recurrence for the number of calls $C(k)$ on the unreachable query, in the worst case.
13. Solve it: show $C(k) \le (2n + 1)^k$ .
14. Compute $\log_2$ of the printed calls of the unreachable query for $n = 4, 8, 16$ and compare with $(\log_2 n)^2$ .
15. From that fit, predict the calls for $n = 32$ and $n = 1{,}024$ . How long would $n = 32$ take at a million calls per second?
16. Why is the time $n^{O(\log n)}$ , more than any polynomial but less than $2^n$ ?
17. The town’s query made only 1,858 calls with 30 places. Why so few?

**Part IV — The trade-off.**

18. Which would you run on the town, and which on a graph given only as a function that returns the neighbours of a vertex, too large to store?
19. Can a deterministic algorithm use $O(\log n)$ space and polynomial time for reachability in directed graphs? What would that say about L and NL?
20. Why does nondeterminism make reachability easy in $O(\log n)$ space?
21. Savitch’s theorem gives $\mathrm{NL} \subseteq \mathrm{SPACE}(\log^2 n)$ . Why is the corresponding statement for time, NP inside a small power of P, not known?
22. Explain how the configuration graph of a machine turns any space-bounded computation into a maze.
23. Why does the result imply $\mathrm{NPSPACE} = \mathrm{PSPACE}$ ?
24. Sum up: what does each method spend, and what does it save?

**Solution of Problem 16.1.**

**1.** $O(n + m)$: each vertex enters the queue once and each edge is looked at once. For the town, 30 places and 105 directed edges: about 135 steps.

**2.** A visited set of 30 places and a queue of at most 30: about 60 numbers of 5 bits, 300 bits; with the visited set as one bit per place, 30 bits plus the queue.

**3.** BFS must not visit a place twice, and in the worst case any place seen may come back; it keeps the whole frontier and the set of places seen, which grow with the map.

**4.** No: on a path the stack holds all $n$ vertices.

**5.** 4 GB for the queue in the worst case, plus 125 MB for a visited bitmap.

**6.** $k = \lceil \log_2 30 \rceil = 5$: a path between two places has at most 29 roads, fewer than $2^5 = 32$.

**7.** $u$, $v$, $w$ (5 bits each for 30 places) and $k$ (3 bits): 18 bits.

**8.** $5 + 1 = 6$, as printed.

**9.** $6 \times 18 = 108$ bits, against about 300 for BFS. Small maps hide the difference: $O(\log^2 n)$ against $O(n \log n)$.

**10.** $k = 30$, 31 frames of $30 + 30 + 30 + 5 = 95$ bits: about 2,950 bits, under 400 bytes, against gigabytes.

**11.** The second half reuses the memory of the first; evaluating both at once would double the memory at every level and make it linear in $n$ again.

**12.** $C(0) = 1$ and $C(k) \le 1 + 2n\,C(k - 1)$: each of $n$ midpoints may need two calls.

**13.** By induction: $1 + 2n(2n + 1)^{k - 1} \le (2n + 1)^{k - 1} + 2n(2n + 1)^{k - 1} = (2n + 1)^k$.

**14.** $\log_2 31 \approx 4.95$, $\log_2 820 \approx 9.68$, $\log_2 88{,}741 \approx 16.44$, against 4, 9 and 16: $\log_2 C \approx (\log_2 n)^2 + 0.5$, so $C \approx 1.4 \, n^{\log_2 n}$.

**15.** $n = 32$: $2^{25.5} \approx 4.5 \times 10^7$ calls, about 45 seconds. $n = 1{,}024$: $2^{100.5} \approx 1.8 \times 10^{30}$ calls, far longer than the age of the universe.

**16.** $n^{\log_2 n} = 2^{(\log_2 n)^2}$: the exponent $(\log_2 n)^2$ outgrows every $c \log_2 n$, so no polynomial bounds it, and stays below $n$, so it is less than $2^n$.

**17.** The place is reachable, and `any` stops at the first midpoint that works. Midpoint $u$ itself works at once for the first half, $R(u, u, k - 1)$, so the recursion soon reduces to shorter questions; the expensive case is a query that fails.

**18.** BFS on the town: it is fast and its memory is tiny anyway. A Savitch-style recursion only where memory is the constraint and the graph is given implicitly, by a function returning neighbours.

**19.** Nobody knows. Directed reachability is complete for NL under [log-space reductions](#def-b3-complexity-classes-logspace), so such an algorithm would give $\mathrm{L} = \mathrm{NL}$.

**20.** A nondeterministic walk guesses the next vertex at each step and keeps only the current vertex and a counter up to $n$: $O(\log n)$ bits.

**21.** Space can be reused: Savitch’s two halves share the same cells. Time cannot: a deterministic simulation of a guessing machine seems to need to try the guesses one after the other, and the only known bound is exponential, $\mathrm{NP} \subseteq \mathrm{EXP}$.

**22.** Its vertices are the configurations, its edges the single steps; the machine accepts if and only if a path leads from the start to the accepting configuration. A machine using space $s$ gives a maze of $2^{O(s)}$ rooms.

**23.** A nondeterministic machine using space $n^c$ is simulated deterministically in space $n^{2c}$, still polynomial: $\mathrm{NPSPACE} \subseteq \mathrm{PSPACE}$, and the other inclusion is immediate.

**24.** BFS spends memory proportional to the graph and saves time, $O(n + m)$; Savitch’s recursion spends time, $n^{O(\log n)}$, and saves memory, $O(\log^2 n)$ bits. On the town both answer at once; the theorem matters when the graph is a configuration graph, far too large to store.
