本书暂未推出简体中文版。现有版本:English。
University Computer Science — Year 3 · 本科三年级
16Time and Space Complexity
Chapter 15 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
means for some constant and all large ; a polynomial bound is for a constant (Year 1 volume). Chapter 15 defined Turing machines with one or several tapes, and showed that one tape simulates 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 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 takes symbols instead of about , and an algorithm that takes steps would look linear when it is exponential in the length of .
Definition 16.2 (Time complexity class, space complexity class, class P)
For a function , the time complexity class is the set of decision problems decided by a multi-tape Turing machine in steps on inputs of size . The space complexity class is the set decided using cells of work tapes, the input being on a read-only tape that does not count. The class P is : the problems decidable in polynomial time.
P is robust: one tape simulates several with a quadratic slowdown (Theorem 15.4), and a random-access machine, or a Python program whose integers stay of polynomial size, is simulated by a Turing machine with a polynomial slowdown too. So whether a problem is in P does not depend on the model, while whether it is in 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 add up to , a search may try all 64 subsets. To be convinced that they do, it is enough to be shown 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 is an algorithm that takes an instance and a word , the certificate, such that is a yes-instance if and only if accepts for some . The class NP is the set of problems that have a verifier running in time polynomial in the size of (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 if and only if a nondeterministic machine decides it in polynomial time, since the machine can guess the certificate one symbol per step, and conversely its choices form a certificate. P is contained in NP: a problem decided in polynomial time has the verifier that ignores the certificate. Whether the inclusion is strict is the question of Chapter 17.
verifiers.py checks certificates 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.
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
$ 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
Without a certificate, the obvious algorithm for subset sum tries every subset. The program search_vs_verify.py builds all subset sums of even numbers, looking for an odd target that is never there; checking a certificate would take steps.
search_vs_verify.py. At the search computes 4,194,304 sums.An optimisation problem becomes a decision problem with a threshold: “what is the shortest tour?” becomes “is there a tour of length at most ?”. If the decision is easy, so is the optimum, by binary search on (Exercise 16.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 for a yes-instance can be found in polynomial time with the help of an oracle that answers the decision problem 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 variables can be found with calls.
Proof. One call checks that is satisfiable. Then, for : let be with set to true and simplified. If the oracle says is satisfiable, keep true and continue with . Otherwise every satisfying assignment of , and there is one by the invariant “the current formula is satisfiable”, has false, so continue with with set to false, without asking. The invariant holds at every step, and after steps all variables are set and the formula is satisfied. ∎
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
$ 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
The oracle here is an exhaustive search, but the algorithm uses only its answers: whatever the oracle costs, finding costs at most 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 computable in time itself, some problem is decided in time but not in time . For a function computable in space , some problem is decided in space but not in space .
Proof idea. The machine , on input padded with symbols, simulates on its own input for steps and does the opposite of what answers. No machine running in time decides the same problem as : on long enough paddings of the simulation finishes and disagrees with . The factor pays for the simulation’s step counter and for moving ’s description along the tapes; the space version needs no such factor. ∎
So is strictly smaller than when , and P is strictly smaller than EXP, the class defined in Section 16.4 (Exercise 16.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 and PSPACE is ; NPSPACE is the same with nondeterministic machines. TQBF is the problem of deciding whether a fully quantified Boolean formula , each being or , is true.
Space can be reused and time cannot, so space is the more generous resource: a machine that runs for steps uses at most cells, and a machine that uses cells has at most configurations, so if it halts it does within that many steps. Hence , and NP is inside PSPACE too (Exercise 16.8).
TQBF is a game. says: the first player can choose so that whatever the second chooses for , the first can choose so that …, and in the end holds. A recursion evaluates it in space proportional to , keeping only one branch at a time: the depth is , the time .
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)
any for , all for . 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
TQBF is in PSPACE, and every problem in PSPACE reduces to it in polynomial time: it is complete for 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 to in a graph of vertices? A nondeterministic machine walks, guessing each next vertex and remembering only the current one and a step counter: bits. Breadth-first search is deterministic but stores a set of up to visited vertices. Savitch’s algorithm stores neither.
Theorem 16.8 (Savitch’s theorem)
Reachability in a directed graph of vertices can be decided deterministically in space . More generally, every problem decided by a nondeterministic machine in space is decided by a deterministic machine in space ; in particular NPSPACE PSPACE.
Proof. Let say that a path of length at most leads from to . holds when or is an edge. For , holds if and only if there is a vertex with and : cut the path in its middle. Compute by this recursion, trying and evaluating the two halves one after the other. A frame stores , , and , bits, and the recursion is frames deep. Paths need at most edges, so suffices: frames of bits. The general statement applies the same recursion to the graph of configurations of the nondeterministic machine, which has vertices, each written in bits (Exercise 16.10). ∎
Walter Savitch published it in 1970.
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))))
$ 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
The memory is tiny and the time is not: on 16 vertices the unreachable query makes 88,741 calls, about . 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 : a deterministic machine with a read-only input and a work tape of 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 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 . The complement, “is there no path?”, seems to need a certificate 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.
16.6 Exercises
Exercise 16.1 ★
For each problem, say what a certificate is and how to check it in polynomial time: (a) the number is composite; (b) the graph has a cycle through every vertex; (c) the graph has vertices that are pairwise adjacent; (d) a partly filled grid of a puzzle can be completed by the rules.
Solution
Solution of Exercise 16.1.
(a) A factor with : one division, polynomial in the number of digits of . (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 vertices: check that they are distinct and that each of the 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 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 .
Solution
Solution of Exercise 16.2.
Decision version: given the distances and a number , is there a tour of length at most ? A tour has legs below , so its length lies in . Binary search on over that interval finds the least with a yes answer, which is the optimum, in about 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 numbers of at most 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 vertices.
Solution
Solution of Exercise 16.3.
(a) bits: the current maximum and an index. (b) The same: the previous number and an index. (c) bits for the copy. (d) bits: a queue of up to vertex numbers and 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
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 that accepts the certificate 0, 1, 0, 1 on the path . Explain why and fix it.
Solution
Solution of Exercise 16.5.
The buggy verifier checks only that the certificate has entries and that consecutive entries are adjacent: 0, 1, 0, 1 has four entries and uses the edge three times, but never visits 2 or 3. The fix requires the certificate to be a permutation of , sorted(order) == list(range(n)), as hamiltonian_path does.
Exercise 16.6 ★★
Write verify_clique(n, edges, k, chosen), a verifier for “the graph has a clique of vertices” running in steps. It is tested against brute force on every small graph.
Solution
Solution of Exercise 16.6.
exercises/ex6_clique.py: reject unless chosen has distinct vertices of the graph; put both directions of every edge in a set, ; then look up each of the pairs, . The test is test_exercise_6_clique.
Exercise 16.7 ★★
Prove that 3-colouring is self-reducible: 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
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 to ; the new graph is 3-colourable exactly when is, and in any colouring the triangle uses all three colours. For each vertex in turn, and for : join to the two triangle vertices other than , and ask the oracle; if it says yes, keep the edges and go to the next vertex, otherwise remove them. If neither nor works, join to and without asking: since the graph was colourable before, some colouring gives one of the three triangle colours, and it was not that of or . The invariant “the current graph is 3-colourable” holds throughout, at most calls are made, and at the end each is forced to the colour of one triangle vertex: reading these gives a 3-colouring of .
Exercise 16.8 ★★
Prove .
Solution
Solution of Exercise 16.8.
Let be a verifier for running in time ; it reads at most symbols of the certificate. On , enumerate the certificates of length at most one after the other, in one buffer of cells, run on each, reusing its space, and accept if one is accepted. The space is for the buffer plus for a run of , 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 vertices, and compare with Output 16.4. Why does the reachable query make fewer calls than the unreachable one?
Solution
Solution of Exercise 16.9.
A call with makes at most calls with , two per midpoint, so with , and . For , : , 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 is simulated deterministically in space . 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
Solution of Exercise 16.10.
Facts used: the input is on a read-only tape and does not count; .
A configuration of the machine on is its state, the position of the input head ( bits), the position of the work head ( bits) and the work tape ( symbols): bits, so there are configurations. The configuration graph has an edge when one step leads from to ; whether it does is decided by looking at the transition table and at the input symbol under ’s input head, in space , without storing the graph. Make the machine erase its tape and move its heads home before accepting, so that there is one accepting configuration . The machine accepts if and only if is reachable from the start configuration, and Savitch’s recursion with decides it with frames of bits: . Computing requires to be computable in space , or trying in turn.
Exercise 16.11 ★★★
Prove from the time hierarchy theorem.
Solution
Solution of Exercise 16.11.
Take . The time hierarchy theorem gives a problem decided in time , so , but in no time . Every problem in P is in for some , and . So is not in P: .
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
Solution of Exercise 16.12.
exercises/ex12_bipartite.py. A walk from back to 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 reaches in the parity graph. That graph has vertices, and an edge for each edge ; the function adjacent reads it from the edge set without building it. The recursion is frames deep, each holding six small numbers, bits: 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.
Part I — Breadth-first search.
- How many steps does BFS take on a graph of vertices and edges? Count them for the town, with each two-way road as two directed edges.
- How much memory does BFS use, in vertices and in bits, when every place is reachable?
- Why can BFS not do with less, when it must remember which places it has seen?
- Depth-first search uses a stack instead of a queue. Is its memory smaller in the worst case?
- With vertices, how much memory does BFS need, at 4 bytes per vertex?
Part II — The midpoint recursion.
- What does
path_existsuse for the town, and why is it enough? - What does one frame store, and how many bits does it need for 30 places?
- Check the printed depth for the town against .
- Bound the total memory in bits, and compare with BFS.
- For , how many frames and how many bytes does the recursion need?
- Why does the recursion evaluate the two halves one after the other rather than both at once?
Part III — What it costs.
- Write a recurrence for the number of calls on the unreachable query, in the worst case.
- Solve it: show .
- Compute of the printed calls of the unreachable query for and compare with .
- From that fit, predict the calls for and . How long would take at a million calls per second?
- Why is the time , more than any polynomial but less than ?
- The town’s query made only 1,858 calls with 30 places. Why so few?
Part IV — The trade-off.
- 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?
- Can a deterministic algorithm use space and polynomial time for reachability in directed graphs? What would that say about L and NL?
- Why does nondeterminism make reachability easy in space?
- Savitch’s theorem gives . Why is the corresponding statement for time, NP inside a small power of P, not known?
- Explain how the configuration graph of a machine turns any space-bounded computation into a maze.
- Why does the result imply ?
- Sum up: what does each method spend, and what does it save?
Solution
Solution of Problem 16.1.
1. : 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 vertices.
5. 4 GB for the queue in the worst case, plus 125 MB for a visited bitmap.
6. : a path between two places has at most 29 roads, fewer than .
7. , , (5 bits each for 30 places) and (3 bits): 18 bits.
8. , as printed.
9. bits, against about 300 for BFS. Small maps hide the difference: against .
10. , 31 frames of 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 again.
12. and : each of midpoints may need two calls.
13. By induction: .
14. , , , against 4, 9 and 16: , so .
15. : calls, about 45 seconds. : calls, far longer than the age of the universe.
16. : the exponent outgrows every , so no polynomial bounds it, and stays below , so it is less than .
17. The place is reachable, and any stops at the first midpoint that works. Midpoint itself works at once for the first half, , 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, so such an algorithm would give .
20. A nondeterministic walk guesses the next vertex at each step and keeps only the current vertex and a counter up to : 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, .
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 gives a maze of rooms.
23. A nondeterministic machine using space is simulated deterministically in space , still polynomial: , and the other inclusion is immediate.
24. BFS spends memory proportional to the graph and saves time, ; Savitch’s recursion spends time, , and saves memory, bits. On the town both answer at once; the theorem matters when the graph is a configuration graph, far too large to store.