Beyond NP: space, hierarchies, randomness and counting
The complexity landscape is much richer than P and NP. Prove hierarchy theorems by diagonalization, study space complexity (L, NL, PSPACE) and Savitch's theorem, PSPACE-completeness of TQBF and generalized games, the polynomial hierarchy, randomized classes BPP, RP and ZPP, the counting class #P and the permanent, and circuit complexity.
After this lesson you can
- Prove the time hierarchy theorem by diagonalization.
- Prove Savitch's theorem and locate reachability in NL.
- Explain why TQBF and generalized games are PSPACE-complete.
- Place problems in BPP, RP, ZPP, #P and the polynomial hierarchy and justify known inclusions.
- Explain what is known and unknown about circuit lower bounds.
Before you start
Motivation: how much harder than NP can a problem be?
Sudoku on an board is NP-complete (Yato and Seta, 2003): if someone gives you the solution, you can check it in a moment. Chess on an board is entirely different. If someone claims White wins from a position, there is no short “certificate” you can check: the proof is a strategy, a tree responding to every possible Black move, and the tree is exponentially large. Fraenkel and Lichtenstein showed in 1981 that generalized chess is EXP-complete. By this lesson’s hierarchy theorem, it has no polynomial algorithm. This is not a conjecture like : it is proved.
There is a subtler second way to go beyond NP. Deciding whether a bipartite graph has a perfect matching is easy: Hopcroft–Karp does it in . But counting perfect matchings is as hard as counting solutions to any NP problem (Valiant, 1979). Probabilistic inference performs counting: a marginal probability in a Bayesian network is a weighted sum over all configurations. That is why exact inference is generally intractable and MCMC and variational methods exist.
Classes P and NP measure one resource (time) with one kind of quantifier (a certificate “exists”). This lesson broadens the picture in four directions:
- Space. How much memory is needed, rather than how many steps? L, NL and PSPACE appear, with a surprising result: for memory, nondeterminism barely helps (Savitch’s theorem).
- Alternation. What happens when “there exists” and “for all” are chained? A fixed number of alternations gives the polynomial hierarchy; a polynomial number gives PSPACE, the class of games.
- Randomness. What can be decided by flipping coins and accepting a small error? RP, coRP, ZPP and BPP.
- Counting. How much does counting cost compared with deciding? The class #P and the permanent.
Above all, there is a question of method: how do we prove something is impossible to do quickly? For separating classes like those in this lesson, the only technique that has worked unconditionally is diagonalization; we will also see why it does not suffice to settle P versus NP.
A map before we start
The map below summarizes the lesson. Each line is a proved inclusion, from bottom to top. The two dashed curves are the only proved separations shown, together with those following from them (such as or ); any equality between two neighboring classes is, separately, compatible with everything known today. Return to it as you progress: by the end of the lesson you should be able to justify every line.
Two observations before the details. First, the central chain has six inclusions and none is individually known to be strict. But forces at least one of the four between P and EXP to be strict, and forces one of the four between NL and PSPACE to be strict. We know there is a jump, but not where. Second, randomized classes (ZPP, RP, BPP) occupy an odd region: BPP could equal P (as conjectured), yet nobody has even proved that it lies within NP.
Diagonalization: more time decides more
The reference model is a deterministic multitape Turing machine. is the class of languages decided by some machine in time on inputs of length . To use as a budget, the machine must be able to measure it: is time-constructible if and there is a machine which, given , writes in binary in time . All reasonable functions are: , , , .
This is Hartmanis and Stearns’ (1965) time hierarchy theorem, refined with the simulation of Hennie and Stearns (1966). The proof is Cantor’s diagonal with a clock, the same idea proving the halting problem undecidable.
Proof
We construct a machine which, on input of length , does the following:
- Compute and start a counter, the clock. Since is constructible, this costs .
- Interpret as : the encoding of a machine followed by arbitrary padding. If has no such form, reject.
- Simulate on itself using a universal machine, subtracting each step from the clock.
- If the simulation finishes before the clock runs out and accepts, rejects. Otherwise (if rejects or the clock runs out), accepts.
always halts in steps, so . Suppose also , decided by a machine in time . The Hennie–Stearns universal simulation executes steps of any multitape machine in steps of its own, with depending only on . Since , there is such that for . Padding permits taking with . On that the simulation finishes in time and is the opposite of , contradicting .
∎The padding makes the proof work: each machine appears infinitely often on the diagonal, with ever longer encodings, and on one of them the clock suffices. Factor is the universal simulation cost; a more efficient universal machine would eliminate it, but it is irrelevant for separating polynomial from exponential classes.
Proof
Every polynomial is , so . Since , the theorem gives .
∎By the same argument, the hierarchy is fine-grained: , and P has no maximum exponent. There are analogous versions for space and nondeterministic machines:
- Space hierarchy (Stearns, Hartmanis and Lewis, 1965). If is space-constructible and , then . Here simulation loses only a constant factor, so no logarithm appears. Corollaries: and .
- Nondeterministic hierarchy (Cook, 1972; Seiferas, Fischer and Meyer, 1978; Žák, 1983). If is time-constructible and , then . The diagonal cannot be reversed directly (negating a nondeterministic machine costs, as far as known, exponential time), and the proof uses “lazy” diagonalization. Corollary: .
Space: L, NL and PSPACE
An algorithm’s space complexity counts its working memory. To discuss sublinear space the input must be separated from memory: the machine reads the input on a read-only tape and only cells on work tapes count.
bits is enough memory for a constant number of input pointers or counters up to . Adding two numbers, checking a palindrome or traversing a tree given as a parent list are L problems. NL adds “guessing”: the typical problem is PATH, reachability in a directed graph. A nondeterministic machine stores the current vertex and a step counter, guesses the next vertex among its neighbors, and accepts if it reaches in fewer than steps. It uses two -bit numbers.
The configuration graph
The tool connecting space and time is the configuration graph. A configuration of a machine on input is a complete snapshot of its state: internal state, input head position, work head position and work tape contents. With work cells and alphabet there are at most
configurations. The graph’s vertices are configurations and there is an arc from to if the machine can move from to in one step. The machine accepts if and only if there is a path from the initial configuration to an accepting one (without loss of generality a single one: erase the tape and bring the heads to the beginning before accepting). Three immediate consequences:
- : breadth-first search suffices on the graph, which has vertices. In particular and .
- : in steps no more than cells are written. Thus , testing certificates one by one and reusing memory.
- PATH is NL-complete under logarithmic-space reductions: an NL machine’s configuration graph can be written in logarithmic space, and deciding the machine amounts to deciding reachability in it.
Savitch’s theorem
Breadth-first search solves PATH in polynomial time but uses bits to mark visited vertices. Can this be done deterministically with much less memory? Savitch (1970) found the answer with a divide-and-conquer idea.
Savitch’s theorem relies on a parameterized question: , “is reachable from in at most steps?” If , just check whether or there is an arc . If , a path of length has a vertex at its midpoint, with both halves of length . Since we do not know which it is, try them all:
The key is that the two recursive calls are sequential: when the first finishes, its memory is freed for the second. At each recursion level only , , the candidate and must be remembered.
Proof
Let be a nondeterministic machine using space . Its configuration graph has vertices, each described by bits, and accepts if and only if with , because a non-repeating path has fewer than arcs. The deterministic machine evaluates with the recursion above. Correctness: if a path of length exists, its vertex at position is a with both halves of length ; and if for some both halves exist, their concatenation is a path of length . Space: recursion has levels, each storing three configurations and a counter, bits; enumerating and checking whether one configuration follows another in one step also fit in . Total . Constructibility of is needed to calculate and know how many cells to reserve.
∎The price is time. If is the number of calls, and : for PATH with vertices, , superpolynomial. Savitch is not a practical algorithm; it proves that nondeterminism, measured in space, costs at most a square. For time, by contrast, the best known result is exponential: we do not know how to simulate NP in deterministic subexponential time.
NL is closed under complement
Savitch shows ; what about complement without losing the square? In 1987 and 1988, Immerman and Szelepcsényi independently proved for ; in particular . The idea is inductive counting: if a nondeterministic machine knows the number of vertices reachable from in steps, it can certify that vertex is not reachable in steps by guessing paths to distinct reachable vertices and checking that none is or has an arc to . With that routine it computes from , storing only a few counters, and with certifies that is unreachable. Many expected this result to be false, and the time counterpart, , is believed false.
The last milestone here is from 2005: Reingold proved reachability in undirected graphs is in L, without randomness, using a construction based on expander graphs. The question , whether directed reachability is in L, remains open.
PSPACE-completeness: quantified formulas and games
A quantified Boolean formula in prenex form is
where is a Boolean formula without quantifiers. Without free variables, is simply true or false. TQBF (true quantified Boolean formulas) is the language of the true ones. If all quantifiers are , it is SAT; if all are , it is TAUT, the coNP-complete problem of tautologies ( is a tautology if and only if is unsatisfiable). With alternation it is different.
Polynomial-time reductions (rather than polynomial-space reductions) are used for the same reason as in NP-completeness: a reduction as powerful as the class would make any nontrivial problem complete.
Proof
TQBF is in PSPACE. The recursive evaluator tries both values of , recursively evaluates the rest in each case and combines with OR if and AND if . Recursion has levels, each storing one bit and its current point; leaves evaluate in polynomial time and space. Total space: .
TQBF is PSPACE-hard. Let be decided by machine in space . Its configurations are encoded with Boolean variables and, as in the Cook–Levin theorem, a polynomial-size formula says “ or moves to in one step” (it is local: each cell depends on three neighboring cells). We want a formula saying “reach from in steps”. The naive version is correct but doubles size at every level. The trick is to use a to write once:
Now , and with : polynomial. Finally, if and only if is true, and moving the quantifiers to the front (the variables are distinct) gives a TQBF instance writable in polynomial time.
∎Notice that the formula is Savitch recursion written in logic: is the midpoint, and over the two pairs permits using the same subformula for both halves, just as Savitch reuses the same stack slot.
Formulas as games
Read as a game between two players choosing values in turn: player sets the existentially quantified variables and wants true; player sets the others and wants it false. The formula is true exactly when has a winning strategy: a rule that, for every history of the opponent’s moves, says what to choose and wins against any response. It is minimax evaluation of the game tree, with nodes as OR and nodes as AND.
The winning strategy for the first formula is a subtree with leaves, one per combination of moves. In general it has leaves: a certificate, but exponential. This distinguishes PSPACE from NP. An NP certificate is a single branch; a PSPACE proof is an entire tree, fitting in polynomial memory only because it is traversed depth-first without being stored.
Generalized games
The connection to real games is direct. In generalized geography, two players move a token in turn along arcs of a directed graph, without revisiting vertices, and whoever cannot move loses (like the children’s word game where each word begins with the previous word’s last letter). Schaefer proved in 1978 that deciding whether the first player wins is PSPACE-complete, reducing from TQBF with a diamond-shaped gadget per variable (the player whose turn it is chooses a side) and a vertex per clause at the end, from which the opponent chooses the clause believed false. Play lasts at most as many moves as vertices, so the problem is in PSPACE.
| Game generalized to an board | Game length | Complexity |
|---|---|---|
| Generalized geography | polynomial (no repeated vertices) | PSPACE-complete (Schaefer, 1978) |
| Hex | polynomial (each cell occupied once) | PSPACE-complete (Reisch, 1981) |
| Othello | polynomial | PSPACE-complete (Iwata and Kasai, 1994) |
| Go without ko, with bounded games | polynomial | PSPACE-hard (Lichtenstein and Sipser, 1980) |
| Checkers | can be exponential | EXP-complete (Robson, 1984) |
| Chess | can be exponential | EXP-complete (Fraenkel and Lichtenstein, 1981) |
| Go with the Japanese ko rule | can be exponential | EXP-complete (Robson, 1983) |
The pattern is clear: if the game has polynomial length, its game tree has polynomial depth, minimax traverses it in polynomial space, and the game is in PSPACE. If games can be exponentially long (pieces move back and forth unhindered), the game rises to EXP, and hierarchy theorems then guarantee no polynomial algorithm.
The polynomial hierarchy
Between NP (one ) and PSPACE (a polynomial number of alternations) is an intermediate staircase: a fixed number of alternations.
, coNP, and by convention . Adding a dummy quantifier shows . An equivalent oracle characterization: , an NP machine allowed free queries to a problem at the previous level. And since TQBF with alternations is in PSPACE, .
Are there natural problems at the second level? Yes, and very close to engineering. Circuit minimization: given a circuit and number , does an equivalent circuit of size to exist? It is written , so it is in . Guessing is not enough for NP, because checking equivalence is coNP-complete. The version for formulas in disjunctive normal form, MIN-DNF, is -complete (Umans, 2001). Its complement, “is this circuit minimal?”, is small on which they differ: .
Proof
Take ; the general case is identical one level up. Suppose and let : . Language is in coNP, hence in NP: there exists with . Then , and two consecutive are one on the pair : . Thus , and by complement . By induction, the same argument absorbs each new quantifier and all levels are NP. If , since P is closed under complement, and the entire hierarchy is P.
∎This is the collapse you can cause in the opening map. The hierarchy is believed infinite, and many results say “if this happens, PH collapses”: a way to say something is unlikely without being able to prove it. One example is Karp and Lipton’s theorem (1980), seen with circuits. Another is that PH cannot have complete problems without collapsing: a PH-complete problem would be in some , and all PH would reduce to that level.
Randomness: RP, coRP, ZPP and BPP
Randomized algorithms from the Las Vegas and Monte Carlo lesson have a class theory. A probabilistic machine is a deterministic machine that receives, besides , a string of uniform independent random bits.
Constants and are arbitrary, and here is the technical heart of randomness: amplification. In RP it is immediate: repeat times and accept if any accepts, leaving error without introducing false positives. In BPP one must vote.
Proof
Let be the number of erroneous runs, the sum of independent Bernoulli variables with means , so . The majority errs only if (counting ties as errors), that is, if . By Hoeffding’s inequality, . To make it , suffices.
∎With (error ), repetitions suffice for error : error falls exponentially with the number of votes. The amplification cell below compares this bound with the exact binomial tail; the bound asks for 10 to 20 % more votes than needed, and the dependence on is real.
Known inclusions
- (do not use randomness), (error amplified to ) and : if , some makes it accept, and that is a certificate verified by executing .
- . You will prove it in the exercises: Markov’s inequality converts expected time into a probability of finishing on time, and conversely the two algorithms alternate until one gives a certain answer.
- (Sipser, 1983; Gács and Lautemann, 1983): after amplification, the set of accepting seeds is so large that a few shifts of it cover the entire seed space, and “there exist shifts such that for every seed one accepts” is a formula.
The most important example of RP and coRP is polynomial identity testing: given an arithmetic circuit computing a polynomial of degree , is ? By the Schwartz–Zippel lemma, if and evaluated at a random point of , . Thus “” is in coRP. Nobody knows how to do it deterministically in polynomial time, and Kabanets and Impagliazzo (2004) showed doing so would imply circuit lower bounds we cannot currently prove.
Randomness and circuits
Proof
Amplify the machine until its error on every input of length is less than ; it uses random bits with polynomial. Fix . For each of length , the fraction of seeds erring on is below . By the union bound, the fraction of seeds erring on any of the inputs is less than . Thus a seed exists that is correct for all inputs of length . Circuit is the machine with hardwired; a machine of time becomes a circuit of size with the same Cook–Levin tableau construction.
∎The proof does not say how to find and therefore gives no algorithm. But it suggests something stronger: if one could deterministically create bits that “look” random to any small circuit, one could dispense with randomness. This is the hardness versus randomness program: Impagliazzo and Wigderson (1997) proved that if some problem in needs circuits of size , then . Therefore the most widespread conjecture is that randomness contributes nothing essential to polynomial-time decision. Historical precedent supports it: primality spent decades in coRP (Miller–Rabin, Solovay–Strassen) and ZPP (Adleman and Huang, 1992) until Agrawal, Kayal and Saxena (2002) gave a deterministic polynomial algorithm.
Counting: #P and the permanent
So far all classes were decision classes: the answer is one bit. Counting solutions produces a number, and its class is Valiant’s (1979).
Being able to count certificates allows decision (check whether the count is positive), so a #P-complete function is at least NP-hard. The Cook–Levin reduction is parsimonious: each accepting computation corresponds to exactly one satisfying assignment. Hence #SAT, counting assignments satisfying a formula, is #P-complete. Unexpectedly, counting can be hard even when deciding is easy:
- Perfect matchings. Deciding existence is in P (with augmenting paths, as in the matching lesson). Counting them is #P-complete (Valiant, 1979).
- 2-SAT. Decision is linear (strongly connected components); counting assignments is #P-complete.
- Simple paths between two vertices: finding one is trivial; counting them is #P-complete.
None of these reductions can be parsimonious from #SAT: a parsimonious reduction would translate “does the formula have any solution?” into “does the graph have a matching?”, and give .
Determinant versus permanent
For a matrix , the determinant and permanent are
They differ only by sign. If is the 0/1 biadjacency matrix of a bipartite graph (rows on the left, columns on the right), each nonzero product corresponds to a perfect matching, and counts them. The determinant is computed in by Gaussian elimination, because elimination respects the alternating structure provided by signs. The permanent lacks that structure, and computing it is #P-complete even for 0/1 matrices.
In the band (ones on the diagonal and its two neighbors), matchings are ways of dividing the row into fixed cells and swapped pairs, and their count follows the Fibonacci recurrence: . Each swap is a transposition with sign , so the determinant sums according to the parity of the number of swaps and nearly cancels. In the complete graph with , the permanent is and determinant 0.
Proof
Expanding the product, , where ranges over all functions from to . Write . The permanent sums over bijections, exactly the functions from to itself whose image is the whole set. By inclusion–exclusion over columns outside the image, the sum over surjective functions is : a function with image appears in all , with total weight , which is 1 if and 0 otherwise.
∎Evaluating the formula as written costs . If subsets are traversed in Gray code, each differs from its predecessor in one column, the row sums update in , and total cost drops to : compared with for brute force, for that is about products versus . It remains exponential and nothing substantially better is known.
How far counting reaches
Counting is powerful. Toda’s theorem (1991) says : a single query to a counting oracle suffices to solve any problem at any level of the polynomial hierarchy. Above that, , because certificates can be enumerated one at a time with a counter.
Approximation is another story, with nuances:
- With an NP oracle, any #P function can be approximated with relative error in randomized polynomial time (Stockmeyer, 1983). Approximate counting is not much harder than deciding.
- For permanents of nonnegative matrices there is a randomized polynomial-time approximation scheme based on MCMC (Jerrum, Sinclair and Vigoda, 2004).
- In planar graphs, perfect matchings can be counted exactly in polynomial time (Kasteleyn, 1961; Temperley and Fisher, 1961): a suitable orientation of edges makes every term of the Pfaffian of the antisymmetric adjacency matrix have the same sign, and the Pfaffian is the square root of a determinant. In a planar bipartite graph it suffices to change the signs of some entries of the biadjacency matrix so equals the permanent.
The Godsil–Gutman estimator in the figure illustrates why approximation is not trivial. If has independent uniform signs , for with 0/1 entries: expanding the square, cross terms of two different permutations have zero expectation and diagonal terms add one per matching. It is unbiased and cheap, but variance can be exponential in , requiring exponentially many samples.
Circuits: P/poly and barriers
A Boolean circuit with inputs computes a Boolean function . An algorithm handles inputs of all lengths; a circuit only one. That is why families are used.
P/poly is a nonuniform model: the circuit for each length can differ and no algorithm is required to construct it. This makes it oddly powerful: it contains all unary languages, including undecidable ones like strings such that machine number halts on an empty tape, because for every the circuit is the appropriate constant. But it also makes it useful for separation: since (a machine of time is a circuit of size ), proving would prove . The hope in the 1980s was that circuits, combinatorial objects without uniformity, would be easier to analyze than machines. Karp and Lipton’s theorem (1980) gives reason to believe NP is not in P/poly: if it were, .
Almost all functions are hard
Proof
There are functions. A circuit with gates is described by choosing, for each gate, one of 16 binary operations and its two inputs among possible sources, then the output gate: at most circuits. With , of that number is for large . Circuits of that size compute at most functions, a fraction tending to 0 of the .
∎This is a pure counting argument, like that for Kolmogorov-incompressible strings: there are more functions than small circuits. For the same count without approximations guarantees functions needing more than 30 000 gates, and Lupanov (1958) proved gates always suffice, so the bound is tight up to a constant factor. The problem is that the argument identifies no concrete function. For explicit NP functions, the best known lower bound on general circuits is linear: about gates (Blum, 1984), improved since only in the coefficient. There is a chasm between and “superpolynomial.”
In restricted models there are strong bounds. Parity cannot be computed by constant-depth polynomial-size circuits with unlimited-fan-in AND and OR gates (class ; Furst, Saxe and Sipser, 1984, and Ajtai, 1983, with Håstad’s exponential bound, 1986). CLIQUE needs superpolynomial-size monotone circuits (without negations) (Razborov, 1985), in fact exponential (Alon and Boppana, 1987). None of these techniques has extended to general circuits.
The three barriers
The failure of half a century of effort to separate P from NP has partial explanations: theorems saying what kind of proof cannot work.
- Relativization (Baker, Gill and Solovay, 1975). Simulation and diagonalization proofs work the same with any oracle, and some oracles give while others do not. Diagonalization alone does not suffice.
- Natural proofs (Razborov and Rudich, 1997). Almost all known circuit lower bounds identify a combinatorial property that is easy to check and possessed by many functions. If cryptographically secure pseudorandom functions exist (as modern cryptography assumes), no such proof can separate NP from P/poly: the property would distinguish pseudorandom functions from random ones.
- Algebrization (Aaronson and Wigderson, 2009). Algebraic techniques that evade relativization (those of ) also do not suffice: they relativize relative to algebraic extensions of the oracles.
The barriers do not say is unprovable; they say a proof will need ideas we do not currently have.
The complete map
Put everything together:
with in parallel. Known strict separations, all by diagonalization: , , and . Everything else is open. A practical way to use the map is to place each problem in the most precise known class:
| Problem | Most precise known class |
|---|---|
| Undirected graph reachability | L (Reingold) |
| Directed graph reachability, 2-SAT | NL-complete |
| Circuit value, linear programming | P-complete |
| Polynomial identity testing | coRP; not known to be in P |
| SAT, clique, Hamiltonian cycle | NP-complete |
| Tautologies (TAUT) | coNP-complete |
| MIN-DNF, circuit minimization | (MIN-DNF is -complete) |
| Count assignments, 0/1 permanent, count matchings | #P-complete |
| TQBF, geography, Hex, polynomial-length games | PSPACE-complete |
| Generalized chess, checkers or Go with unbounded games | EXP-complete |
Implementation from scratch
Savitch versus breadth-first search
First, Savitch recursion as written, instrumented to count calls and maximum stack depth, on directed paths of vertices. Each query is made in both directions: forward the destination is reachable, backward it is not.
from collections import deque
def alcanza_savitch(adj, n, u, v, k, est, prof=1):
"""¿Hay camino de u a v con como mucho 2**k arcos? Recursión sobre el punto medio."""
est["llamadas"] += 1
est["prof_max"] = max(est["prof_max"], prof)
if k == 0:
return u == v or v in adj[u]
for w in range(n): # se prueban todos los puntos medios, en orden
if (alcanza_savitch(adj, n, u, w, k - 1, est, prof + 1)
and alcanza_savitch(adj, n, w, v, k - 1, est, prof + 1)):
return True
return False
def alcanza_bfs(adj, n, s, t):
visto = [False] * n # n bits de memoria: lo que Savitch evita
visto[s] = True
cola = deque([s])
while cola:
u = cola.popleft()
for v in adj[u]:
if not visto[v]:
visto[v] = True
cola.append(v)
return visto[t]
print(f"{'n':>3} {'k':>2} {'pregunta':>9} {'resp.':>6} {'llamadas':>9} {'(2n)^k':>9} {'prof. máx':>9} {'bits pila':>9} {'bits BFS':>8}")
for n in [4, 8, 16]:
adj = [{i + 1} if i + 1 < n else set() for i in range(n)] # camino dirigido 0 → 1 → ... → n-1
k = (n - 1).bit_length() # 2**k >= n - 1
b = (n - 1).bit_length() # bits por vértice
for s, t in [(0, n - 1), (n - 1, 0)]:
est = {"llamadas": 0, "prof_max": 0}
r = alcanza_savitch(adj, n, s, t, k, est)
assert r == alcanza_bfs(adj, n, s, t)
print(f"{n:>3} {k:>2} {f'{s}→{t}':>9} {str(r):>6} {est['llamadas']:>9} {(2 * n) ** k:>9} "
f"{est['prof_max']:>9} {est['prof_max'] * 3 * b:>9} {n:>8}")Depth is always , while calls rise from dozens to nearly as vertices increase from 4 to 16, below bound but growing at the same rate. At these sizes breadth-first search uses fewer bits than Savitch ( versus ); Savitch’s advantage is asymptotic, and by the figure’s count begins around .
TQBF and geography with polynomial space
The quantified formula evaluator traverses the game tree depth-first. The stack stores only the partial assignment, so depth is the variable count; time, by contrast, is tree size. With poda=False both children are always evaluated and the entire tree appears; with poda=True, an stops upon finding a true child and a upon finding a false one.
import random
import time
def evalua_qbf(cuant, clausulas, asig=(), est=None, poda=True):
"""Valor de Q1 x1 ... Qn xn φ con φ en FNC (literales ±i para x_i)."""
est["nodos"] += 1
est["prof_max"] = max(est["prof_max"], len(asig))
i = len(asig)
if i == len(cuant):
return all(any((asig[abs(l) - 1] == 1) == (l > 0) for l in c) for c in clausulas)
hijos = (evalua_qbf(cuant, clausulas, asig + (b,), est, poda) for b in (0, 1))
if not poda:
hijos = list(hijos) # fuerza a evaluar los dos hijos
return any(hijos) if cuant[i] == "E" else all(hijos)
def qbf_aleatoria(n, m, rng):
cuant = ["E" if i % 2 == 0 else "A" for i in range(n)]
cl = [[v if rng.random() < 0.5 else -v for v in rng.sample(range(1, n + 1), 3)] for _ in range(m)]
return cuant, cl
rng = random.Random(2)
print(f"{'n':>3} {'valor':>6} {'nodos (sin poda)':>17} {'ms':>7} {'nodos (poda)':>13} {'prof. máx':>9}")
for n in [8, 10, 12, 14, 16]:
cuant, cl = qbf_aleatoria(n, n // 2, rng)
est0 = {"nodos": 0, "prof_max": 0}
t0 = time.perf_counter()
v0 = evalua_qbf(cuant, cl, (), est0, poda=False)
ms = 1000 * (time.perf_counter() - t0)
est1 = {"nodos": 0, "prof_max": 0}
v1 = evalua_qbf(cuant, cl, (), est1, poda=True)
assert v0 == v1
print(f"{n:>3} {str(v0):>6} {est0['nodos']:>17} {ms:>7.0f} {est1['nodos']:>13} {est1['prof_max']:>9}")
def gana_quien_mueve(adj, v, usados, est, prof=1):
"""Geografía generalizada: quien mueve está en v y pierde si no tiene arco a un vértice sin usar."""
est["nodos"] += 1
est["prof_max"] = max(est["prof_max"], prof)
for w in adj[v]:
if w not in usados:
usados.add(w)
rival_gana = gana_quien_mueve(adj, w, usados, est, prof + 1)
usados.remove(w) # se deshace la jugada: el espacio se reutiliza
if not rival_gana:
return True # una jugada que deja al rival en posición perdedora
return False
animales = ["gato", "oso", "oveja", "ardilla", "avestruz", "zorro", "orca", "alce", "erizo",
"oca", "anguila", "atún", "nutria", "araña", "abeja", "elefante", "escorpión", "nandú"]
adj = {p: [q for q in animales if q != p and q[0] == p[-1]] for p in animales}
est = {"nodos": 0, "prof_max": 0}
gana_segundo = gana_quien_mueve(adj, "gato", {"gato"}, est) # el primero ya ha dicho «gato»
print(f"\ngeografía con {len(animales)} animales empezando por «gato»: gana el "
f"{'segundo' if gana_segundo else 'primero'} jugador ({est['nodos']} posiciones, profundidad máxima {est['prof_max']})")Without pruning, nodes are exactly and time quadruples every two variables; depth never exceeds . Pruning greatly reduces the tree in these instances, but in the worst case does not change exponential growth (otherwise TQBF would be in P). In animal geography, the solver traverses about five thousand positions with stack depth 16: the longest game length, not the number of positions.
Amplifying BPP: bound versus exact value
How many repetitions reduce majority error to ? The exact binomial tail is computed using the incomplete beta function, . Three numbers are compared: Hoeffding’s bound , Chernoff’s using Kullback–Leibler divergence , and the exact minimum odd .
import math
from scipy.special import betainc
def error_mayoria(k, p):
"""P[al menos la mitad de k ejecuciones fallan] si cada una falla con probabilidad p."""
m = math.ceil(k / 2)
return betainc(m, k - m + 1, p)
def k_impar_minimo(p, objetivo):
"""Menor k impar con error de la mayoría <= objetivo (para k impar el error decrece con k)."""
lo, hi = 0, 1
while error_mayoria(2 * hi + 1, p) > objetivo:
hi *= 2
while lo < hi:
mid = (lo + hi) // 2
if error_mayoria(2 * mid + 1, p) <= objetivo:
hi = mid
else:
lo = mid + 1
return 2 * lo + 1
objetivo = 2.0 ** -40
print(f"{'p':>6} {'delta':>6} {'Hoeffding':>10} {'Chernoff-KL':>12} {'exacto':>8}")
for p in [1 / 3, 0.4, 0.45, 0.49]:
d = 0.5 - p
hoeff = math.ceil(math.log(1 / objetivo) / (2 * d * d))
kl = 0.5 * math.log(0.5 / p) + 0.5 * math.log(0.5 / (1 - p))
cher = math.ceil(math.log(1 / objetivo) / kl)
print(f"{p:>6.3f} {d:>6.3f} {hoeff:>10} {cher:>12} {k_impar_minimo(p, objetivo):>8}")All three columns grow like : moving from to multiplies the vote count by about one hundred. Hoeffding’s bound is easiest to use and least tight; Kullback–Leibler gives the correct exponent (the large deviations rate), and the remaining difference from the exact value is a polynomial factor not captured by the exponential bound.
Counting versus deciding
Now the contrast motivating #P. Deciding whether a perfect matching exists uses SciPy’s maximum_bipartite_matching, implementing Hopcroft–Karp. Counting uses Ryser’s formula in Gray code, programmed from scratch and validated against brute force.
import itertools
import time
import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import maximum_bipartite_matching
def ryser(A):
"""Permanente por inclusión-exclusión con código Gray: O(2^n n) operaciones."""
n = len(A)
sumas = [0] * n # sumas de cada fila sobre las columnas del subconjunto
total, gris_prev = 0, 0
for k in range(1, 1 << n):
gris = k ^ (k >> 1)
j = (gris ^ gris_prev).bit_length() - 1 # la única columna que entra o sale
d = 1 if gris >> j & 1 else -1
for i in range(n):
sumas[i] += d * A[i][j]
gris_prev = gris
prod = 1
for s in sumas:
prod *= s
if prod == 0:
break
total += prod if (n - bin(gris).count("1")) % 2 == 0 else -prod
return total
def perm_fuerza_bruta(A):
n = len(A)
return sum(all(A[i][s[i]] for i in range(n)) for s in itertools.permutations(range(n)))
def hay_perfecto(A):
M = maximum_bipartite_matching(csr_matrix(np.asarray(A)), perm_type="column")
return bool(np.all(M >= 0))
rng = np.random.default_rng(0)
for n in range(1, 8):
for _ in range(20):
A = (rng.random((n, n)) < 0.5).astype(int).tolist()
assert ryser(A) == perm_fuerza_bruta(A)
assert (ryser(A) > 0) == hay_perfecto(A)
print("Ryser coincide con la fuerza bruta, y perm > 0 con la decisión, en 140 matrices aleatorias")
print(f"\n{'n':>3} {'decidir (ms)':>13} {'contar (ms)':>12} {'perm':>12}")
for n in [8, 10, 12, 14, 16]:
A = (rng.random((n, n)) < 0.5).astype(int)
t0 = time.perf_counter(); hay_perfecto(A); td = 1000 * (time.perf_counter() - t0)
t0 = time.perf_counter(); p = ryser(A.tolist()); tc = 1000 * (time.perf_counter() - t0)
print(f"{n:>3} {td:>13.2f} {tc:>12.1f} {p:>12}")
A = ((rng.random((2000, 2000)) < 0.002) | np.eye(2000, dtype=bool)).astype(int) # la diagonal garantiza un «sí»
t0 = time.perf_counter()
d = hay_perfecto(A)
print(f"\ndecidir con n = 2000 y {A.sum()} aristas: {d}, {1000 * (time.perf_counter() - t0):.0f} ms")Ryser’s time multiplies by just over four whenever grows by 2, as predicted by , while deciding takes around a millisecond or less and stays instantaneous with 2000 vertices per side and about 10 000 edges (the diagonal ensures the answer is “yes,” so the algorithm must construct an entire perfect matching). With , Ryser counting would require about steps.
Finally, the Godsil–Gutman estimator on three matrices, with 4000 samples each. The determinant of a matrix batch is computed all at once with NumPy.
import numpy as np
def godsil_gutman(A, muestras, rng):
A = np.asarray(A, dtype=float)
S = rng.choice([-1.0, 1.0], size=(muestras,) + A.shape)
return np.linalg.det(S * A) ** 2 # una muestra de det(A∘S)² por matriz de signos
rng = np.random.default_rng(1)
casos = {
"banda 12×12": np.eye(12) + np.eye(12, k=1) + np.eye(12, k=-1),
"aleatoria 12×12": (rng.random((12, 12)) < 0.5).astype(float),
"completa 8×8": np.ones((8, 8)),
}
for nombre, A in casos.items():
exacta = ryser(A.astype(int).tolist())
X = godsil_gutman(A, 4000, rng)
print(f"{nombre:>16}: perm = {exacta:>6} estimación = {X.mean():>9.1f} ± {X.std() / np.sqrt(len(X)):>6.1f}"
f" desv. típica / perm = {X.std() / exacta:.2f}")The band has matchings, and the three estimates fall within a few standard deviations of the exact value. But the standard deviation of a single sample is several times the permanent itself, so a 1 % relative error would require between about and samples (the square of that ratio times ) even on these small matrices, and for bad families the ratio grows exponentially with .
With libraries
| Task | Tool | Comment |
|---|---|---|
| Decide perfect matching | scipy.sparse.csgraph.maximum_bipartite_matching | Hopcroft–Karp on sparse matrices |
| Exact permanent | sympy.Matrix.per() | exact on integers; exponential like Ryser |
| Count models of a formula | sharpSAT, d4, Ganak | knowledge compilers and exact counters; exploit structure |
| Solve QBF | DepQBF, CAQE | QBF solvers with clause learning |
import numpy as np
from sympy import Matrix
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import maximum_bipartite_matching
banda = np.eye(8, dtype=int) + np.eye(8, k=1, dtype=int) + np.eye(8, k=-1, dtype=int)
print("perm de la banda 8×8 con SymPy:", Matrix(banda).per(), " con Ryser:", ryser(banda.tolist()))
print("det de la banda 8×8:", round(np.linalg.det(banda)))
emp = maximum_bipartite_matching(csr_matrix(banda), perm_type="column")
print("un emparejamiento perfecto (columna de cada fila):", emp.tolist())Industrial model counters and QBF solvers are unavailable in the browser, but their lesson is that of the table: they do not change worst-case complexity, but exploit the structure of real instances (independent components, subformula caches, small treewidth).
Typical mistakes
Exercises
More than one answer may be correct.
More than one answer may be correct.
Step 1 of 4. To what problem do you reduce acceptance by ?
Step 1 of 4. Let be a ZPP algorithm for with expected time . How do you obtain an RP algorithm?
permanente(A) using Ryser's formula, , in operations (Gray code) or at least . A is a list of lists of integers of size with . Do not use itertools.permutations: the tests compare with the definition on small matrices and require a matrix of in less than one second.def permanente(A):
"""Permanente de la matriz cuadrada A (lista de listas de enteros) por la fórmula de Ryser."""
n = len(A)
total = 0
# recorre los subconjuntos S de columnas (máscaras de 1 a 2**n - 1),
# calcula el producto de las sumas de fila restringidas a S
# y súmalo con el signo (-1)**(n - |S|)
return totalSummary
- Hierarchy theorems, proved by diagonalization with a clock, guarantee that more time or space decides more: and . Diagonalization relativizes and therefore does not suffice for P versus NP.
- The configuration graph connects space and time: configurations yield . Savitch tries every midpoint and reuses the stack: and . Immerman and Szelepcsényi: .
- TQBF is PSPACE-complete; its proof is Savitch recursion written with quantifiers. A quantified formula is a game, and games with polynomial-length play are PSPACE-complete; with exponential play, EXP-complete.
- The polynomial hierarchy counts fixed alternations of and ; circuit minimization lives in , and if the entire hierarchy collapses to P.
- RP and coRP have one-sided error, BPP two-sided error with a polynomial margin over 1/2, and ZPP never errs; , , and is conjectured.
- Counting can be #P-complete even when deciding is easy: the permanent differs from the determinant only in signs, and Ryser computes it in . The entire polynomial hierarchy fits in .
- Almost all functions require exponential circuits (Shannon), but we cannot identify any NP function needing more than about gates; the barriers of relativization, natural proofs and algebrization explain part of the difficulty.