Module contents
Lesson 29 of 33Advanced 110 min

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 n2×n2n^2 \times n^2 board is NP-complete (Yato and Seta, 2003): if someone gives you the solution, you can check it in a moment. Chess on an n×nn \times n 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 P≠NP\mathsf{P} \neq \mathsf{NP}: 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 O(mn)\bigO(m\sqrt{n}). 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 L≠PSPACE\mathsf{L} \neq \mathsf{PSPACE} or NL≠EXP\mathsf{NL} \neq \mathsf{EXP}); 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.

InteractiveThe complexity class map
≠time hierarchy≠space hierarchyEXPPSPACEP#PPHΣ₂pΠ₂pNPBPPcoNPRPcoRPZPPPNLL
  • selected class
  • contain it
  • contained in it
  • proven strict inclusion
NP: Nondeterministic polynomial time
Problems whose yes instances have a short certificate verifiable in polynomial time.
Contained in: Π2p\Pi_2^p, Σ2p\Sigma_2^p, PH, P#P\mathsf{P}^{\#\mathsf{P}}, PSPACE, EXP · Contains: L, NL, P, ZPP, RP
Representative problem. SAT and the thousands of problems reducible to it: clique, 3-coloring, Hamiltonian cycle and subset sum.
Proven. RP⊆NP\mathsf{RP} \subseteq \mathsf{NP}: a random seed leading to acceptance is a certificate.
Open. Is P=NP\mathsf{P} = \mathsf{NP}? Is NP=coNP\mathsf{NP} = \mathsf{coNP}? Is BPP contained in NP? These remain unknown.
Assumption
Selected classNP
Classes containing it6
Classes it contains5
Distinct classes on the map15 of 15
Click a class: blue highlights those containing it and aqua those it contains, and below are a representative problem, what is proved and what remains open. Then choose an assumption. What collapses if P=NP\mathsf{P} = \mathsf{NP}? Why does EXP stay put? What must happen between L and P if P=PSPACE\mathsf{P} = \mathsf{PSPACE}?

Two observations before the details. First, the central chain L⊆NL⊆P⊆NP⊆PH⊆PSPACE⊆EXP\mathsf{L} \subseteq \mathsf{NL} \subseteq \mathsf{P} \subseteq \mathsf{NP} \subseteq \mathsf{PH} \subseteq \mathsf{PSPACE} \subseteq \mathsf{EXP} has six inclusions and none is individually known to be strict. But P≠EXP\mathsf{P} \neq \mathsf{EXP} forces at least one of the four between P and EXP to be strict, and NL≠PSPACE\mathsf{NL} \neq \mathsf{PSPACE} 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. TIME(f(n))\mathsf{TIME}(f(n)) is the class of languages decided by some machine in time O(f(n))\bigO(f(n)) on inputs of length nn. To use ff as a budget, the machine must be able to measure it: ff is time-constructible if f(n)≥nf(n) \ge n and there is a machine which, given 1n1^n, writes f(n)f(n) in binary in time O(f(n))\bigO(f(n)). All reasonable functions are: n2n^2, nlog⁡nn \log n, 2n2^n, n!n!.

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 DD which, on input xx of length nn, does the following:

  1. Compute f(n)f(n) and start a counter, the clock. Since ff is constructible, this costs O(f(n))\bigO(f(n)).
  2. Interpret xx as ⟨M⟩10j\langle M\rangle 1 0^j: the encoding of a machine MM followed by arbitrary padding. If xx has no such form, reject.
  3. Simulate MM on xx itself using a universal machine, subtracting each step from the clock.
  4. If the simulation finishes before the clock runs out and MM accepts, DD rejects. Otherwise (if MM rejects or the clock runs out), DD accepts.

DD always halts in O(f(n))\bigO(f(n)) steps, so L(D)∈TIME(f(n))L(D) \in \mathsf{TIME}(f(n)). Suppose also L(D)∈TIME(g(n))L(D) \in \mathsf{TIME}(g(n)), decided by a machine MM in time c g(n)c\,g(n). The Hennie–Stearns universal simulation executes tt steps of any multitape machine in cM tlog⁡tc_M\, t\log t steps of its own, with cMc_M depending only on MM. Since glog⁡g=o(f)g\log g = o(f), there is n0n_0 such that cM c g(n)log⁡(c g(n))<f(n)c_M\, c\,g(n)\log(c\,g(n)) < f(n) for n≥n0n \ge n_0. Padding permits taking x=⟨M⟩10jx = \langle M\rangle 1 0^j with ∣x∣≥n0\abs{x} \ge n_0. On that xx the simulation finishes in time and D(x)D(x) is the opposite of M(x)M(x), contradicting L(D)=L(M)L(D) = L(M).

∎

The padding 0j0^j 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 log⁡g\log g 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 O(2n)\bigO(2^n), so P⊆TIME(2n)\mathsf{P} \subseteq \mathsf{TIME}(2^n). Since 2n⋅n=o(22n)2^n \cdot n = o(2^{2n}), the theorem gives TIME(2n)⊊TIME(22n)⊆EXP\mathsf{TIME}(2^n) \subsetneq \mathsf{TIME}(2^{2n}) \subseteq \mathsf{EXP}.

∎

By the same argument, the hierarchy is fine-grained: TIME(n2)⊊TIME(n2.01)\mathsf{TIME}(n^2) \subsetneq \mathsf{TIME}(n^{2.01}), and P has no maximum exponent. There are analogous versions for space and nondeterministic machines:

  • Space hierarchy (Stearns, Hartmanis and Lewis, 1965). If f(n)≥log⁡nf(n) \ge \log n is space-constructible and g=o(f)g = o(f), then SPACE(g(n))⊊SPACE(f(n))\mathsf{SPACE}(g(n)) \subsetneq \mathsf{SPACE}(f(n)). Here simulation loses only a constant factor, so no logarithm appears. Corollaries: L⊊PSPACE\mathsf{L} \subsetneq \mathsf{PSPACE} and PSPACE⊊EXPSPACE\mathsf{PSPACE} \subsetneq \mathsf{EXPSPACE}.
  • Nondeterministic hierarchy (Cook, 1972; Seiferas, Fischer and Meyer, 1978; Žák, 1983). If ff is time-constructible and g(n+1)=o(f(n))g(n+1) = o(f(n)), then NTIME(g)⊊NTIME(f)\mathsf{NTIME}(g) \subsetneq \mathsf{NTIME}(f). The diagonal cannot be reversed directly (negating a nondeterministic machine costs, as far as known, exponential time), and the proof uses “lazy” diagonalization. Corollary: NP⊊NEXP\mathsf{NP} \subsetneq \mathsf{NEXP}.

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.

O(log⁡n)\bigO(\log n) bits is enough memory for a constant number of input pointers or counters up to nn. 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 tt in fewer than nn steps. It uses two log⁡n\log n-bit numbers.

The configuration graph

The tool connecting space and time is the configuration graph. A configuration of a machine on input xx is a complete snapshot of its state: internal state, input head position, work head position and work tape contents. With s(n)s(n) work cells and alphabet Γ\Gamma there are at most

∣Q∣⋅(n+2)⋅s(n)⋅∣Γ∣s(n)=2O(s(n))si s(n)≥log⁡n\abs{Q}\cdot(n+2)\cdot s(n)\cdot\abs{\Gamma}^{s(n)} = 2^{\bigO(s(n))} \quad \text{si } s(n) \ge \log n

configurations. The graph’s vertices are configurations and there is an arc from cc to c′c' if the machine can move from cc to c′c' in one step. The machine accepts xx 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:

  • NSPACE(s)⊆TIME(2O(s))\mathsf{NSPACE}(s) \subseteq \mathsf{TIME}(2^{\bigO(s)}): breadth-first search suffices on the graph, which has 2O(s)2^{\bigO(s)} vertices. In particular NL⊆P\mathsf{NL} \subseteq \mathsf{P} and PSPACE⊆EXP\mathsf{PSPACE} \subseteq \mathsf{EXP}.
  • TIME(t)⊆SPACE(t)\mathsf{TIME}(t) \subseteq \mathsf{SPACE}(t): in tt steps no more than tt cells are written. Thus NP⊆PSPACE\mathsf{NP} \subseteq \mathsf{PSPACE}, 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 nn 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: \textscReach(u,v,k)\textsc{Reach}(u, v, k), “is vv reachable from uu in at most 2k2^k steps?” If k=0k = 0, just check whether u=vu = v or there is an arc u→vu \to v. If k>0k > 0, a path of length ≤2k\le 2^k has a vertex ww at its midpoint, with both halves of length ≤2k−1\le 2^{k-1}. Since we do not know which ww it is, try them all:

\textscReach(u,v,k)=⋁w[\textscReach(u,w,k−1)∧\textscReach(w,v,k−1)].\textsc{Reach}(u, v, k) = \bigvee_{w} \Big[\textsc{Reach}(u, w, k-1) \wedge \textsc{Reach}(w, v, k-1)\Big].

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 uu, vv, the candidate ww and kk must be remembered.

InteractiveSavitch recursion
asourcebcdetargetStack: 3 slots of three registers of 3 bitsk = 2≤ 4 stepsu000v100w···k = 1≤ 2 stepsu···v···w···k = 0≤ 1 stepsu···v···
  • call source uu
  • target vv
  • midpoint ww being tested
  • edge confirming base case
  • missing edge
1 / 27
Initial question: can e be reached from a in at most 22=42^{2} = 4 steps? Midpoints ww = a, b, c… are tried in order; for each, both halves get half the steps.
Configuration graph
20
Calls made1 of 22
Stack depth (limit K+1=3K + 1 = 3)1
Maximum depth reached1
Bits in full stack3 × 3 × 3 = 27
Answer…
Savitch with N=220N = 2^{20}1 260 bits
Mark visited (BFS)220 bits2^{20}\ \text{bits}
BFS / Savitch832 ×
Uses less memorySavitch
Each stack frame stores the uu, vv and ww registers of a call in binary. Replay the recursion: midpoint ww visits vertices in order and each test opens a new frame below, released upon return. Does the depth ever exceed K+1K + 1? Compare the call count in the long and unreachable graph: time grows like NKN^K, space like Klog⁡NK \log N. Use the slider to compare Savitch memory with the NN bits of breadth-first search: at what size does Savitch win?
Proof

Let MM be a nondeterministic machine using space s(n)s(n). Its configuration graph has N≤2c s(n)N \le 2^{c\,s(n)} vertices, each described by O(s(n))\bigO(s(n)) bits, and MM accepts xx if and only if \textscReach(cini,cacc,K)\textsc{Reach}(c_{\text{ini}}, c_{\text{acc}}, K) with K=⌈c s(n)⌉K = \lceil c\,s(n)\rceil, because a non-repeating path has fewer than N≤2KN \le 2^K arcs. The deterministic machine evaluates \textscReach\textsc{Reach} with the recursion above. Correctness: if a path of length ℓ≤2k\ell \le 2^k exists, its vertex at position ⌈ℓ/2⌉\lceil \ell/2\rceil is a ww with both halves of length ≤2k−1\le 2^{k-1}; and if for some ww both halves exist, their concatenation is a path of length ≤2k\le 2^k. Space: recursion has K+1K + 1 levels, each storing three configurations and a counter, O(s(n))\bigO(s(n)) bits; enumerating ww and checking whether one configuration follows another in one step also fit in O(s(n))\bigO(s(n)). Total O(K⋅s(n))=O(s(n)2)\bigO(K \cdot s(n)) = \bigO(s(n)^2). Constructibility of ss is needed to calculate KK and know how many cells to reserve.

∎

The price is time. If T(k)T(k) is the number of calls, T(k)≤2N T(k−1)T(k) \le 2N\,T(k-1) and T(K)≤(2N)K=2O(s2)T(K) \le (2N)^K = 2^{\bigO(s^2)}: for PATH with N=nN = n vertices, nO(log⁡n)n^{\bigO(\log n)}, 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 NSPACE(s)⊆SPACE(s2)\mathsf{NSPACE}(s) \subseteq \mathsf{SPACE}(s^2); what about complement without losing the square? In 1987 and 1988, Immerman and Szelepcsényi independently proved NSPACE(s)=coNSPACE(s)\mathsf{NSPACE}(s) = \mathsf{coNSPACE}(s) for s≥log⁡ns \ge \log n; in particular NL=coNL\mathsf{NL} = \mathsf{coNL}. The idea is inductive counting: if a nondeterministic machine knows the number cic_i of vertices reachable from ss in ≤i\le i steps, it can certify that vertex vv is not reachable in ≤i+1\le i + 1 steps by guessing paths to cic_i distinct reachable vertices and checking that none is vv or has an arc to vv. With that routine it computes ci+1c_{i+1} from cic_i, storing only a few counters, and with cnc_n certifies that tt is unreachable. Many expected this result to be false, and the time counterpart, NP=coNP\mathsf{NP} = \mathsf{coNP}, 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 L=NL\mathsf{L} = \mathsf{NL}, whether directed reachability is in L, remains open.

PSPACE-completeness: quantified formulas and games

A quantified Boolean formula in prenex form is

Φ=Q1x1 Q2x2⋯Qnxn  φ(x1,…,xn),Qi∈{∃,∀},\Phi = Q_1 x_1\, Q_2 x_2 \cdots Q_n x_n\; \varphi(x_1, \dots, x_n), \qquad Q_i \in \{\exists, \forall\},

where φ\varphi is a Boolean formula without quantifiers. Without free variables, Φ\Phi is simply true or false. TQBF (true quantified Boolean formulas) is the language of the true ones. If all quantifiers are ∃\exists, it is SAT; if all are ∀\forall, it is TAUT, the coNP-complete problem of tautologies (φ\varphi is a tautology if and only if ¬φ\neg\varphi 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 x1x_1, recursively evaluates the rest in each case and combines with OR if Q1=∃Q_1 = \exists and AND if Q1=∀Q_1 = \forall. Recursion has nn levels, each storing one bit and its current point; leaves evaluate φ\varphi in polynomial time and space. Total space: O(n+∣φ∣)\bigO(n + \abs{\varphi}).

TQBF is PSPACE-hard. Let AA be decided by machine MM in space s(n)=ncs(n) = n^c. Its configurations are encoded with m=O(s(n))m = \bigO(s(n)) Boolean variables and, as in the Cook–Levin theorem, a polynomial-size formula φ0(a,b)\varphi_0(a, b) says “a=ba = b or aa moves to bb in one step” (it is local: each cell depends on three neighboring cells). We want a formula φk(a,b)\varphi_k(a, b) saying “reach bb from aa in ≤2k\le 2^k steps”. The naive version φk(a,b)=∃w [φk−1(a,w)∧φk−1(w,b)]\varphi_k(a, b) = \exists w\,[\varphi_{k-1}(a, w) \wedge \varphi_{k-1}(w, b)] is correct but doubles size at every level. The trick is to use a ∀\forall to write φk−1\varphi_{k-1} once:

φk(a,b)=∃w  ∀c ∀d  [((c=a∧d=w)∨(c=w∧d=b))⇒φk−1(c,d)].\varphi_k(a, b) = \exists w\; \forall c\, \forall d\; \Big[\big((c = a \wedge d = w) \vee (c = w \wedge d = b)\big) \Rightarrow \varphi_{k-1}(c, d)\Big].

Now ∣φk∣=∣φk−1∣+O(m)\abs{\varphi_k} = \abs{\varphi_{k-1}} + \bigO(m), and ∣φK∣=O(mK+∣φ0∣)\abs{\varphi_K} = \bigO(m K + \abs{\varphi_0}) with K=O(s(n))K = \bigO(s(n)): polynomial. Finally, x∈Ax \in A if and only if φK(cini,cacc)\varphi_K(c_{\text{ini}}, c_{\text{acc}}) 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: ∃w\exists w is the midpoint, and ∀\forall over the two pairs (c,d)(c, d) permits using the same subformula for both halves, just as Savitch reuses the same stack slot.

Formulas as games

Read ∃x1∀x2∃x3∀x4  φ\exists x_1 \forall x_2 \exists x_3 \forall x_4\; \varphi as a game between two players choosing values in turn: player ∃\exists sets the existentially quantified variables and wants φ\varphi true; player ∀\forall sets the others and wants it false. The formula is true exactly when ∃\exists 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 ∃\exists nodes as OR and ∀\forall nodes as AND.

InteractiveTQBF as a game
∃x1 ∀x2 ∃x3 ∀x4    (x1∨x2)∧(¬x2∨¬x3)∧(x2∨x3∨¬x4)\exists x_1\,\forall x_2\,\exists x_3\,\forall x_4\;\; (x_1 \lor x_2) \land (\neg x_2 \lor \neg x_3) \land (x_2 \lor x_3 \lor \neg x_4)
C1=(x1∨x2)C_1 = (x_1 \lor x_2) C2=(¬x2∨¬x3)C_2 = (\neg x_2 \lor \neg x_3) C3=(x2∨x3∨¬x4)C_3 = (x_2 \lor x_3 \lor \neg x_4)
010101∃∀∀∃∃∃∃∀∀∀∀∀∀∀∀FFFFTTFFTFTTTTFFx1x2x3x4
  • true
  • false
  • played game
  • winning strategy
Your turn: choose x1x_1 (playing as ∃).
Formula
Play as
Turnyou (∃), x1
Assignment· · · ·
Formula valuehidden
As SAT (all ∃)satisfiable
Tree nodes (minimax)31
Stack depth5
Strategy leaves4=224 = 2^{2}
Games won0 of 0
Play as ∃\exists against a machine playing ∀\forall optimally. With the first formula you can always win, but only if you choose x1x_1 well and respond to x2x_2 with the right x3x_3: what is the rule? With the second, satisfiable as SAT, you lose whatever you do: what ∀\forall move ruins you? Activate the winning strategy and count its leaves, then switch sides to play as ∀\forall.

The winning strategy for the first formula is a subtree with 22=42^2 = 4 leaves, one per combination of ∀\forall moves. In general it has 2#∀2^{\#\forall} 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 n×nn \times n boardGame lengthComplexity
Generalized geographypolynomial (no repeated vertices)PSPACE-complete (Schaefer, 1978)
Hexpolynomial (each cell occupied once)PSPACE-complete (Reisch, 1981)
OthellopolynomialPSPACE-complete (Iwata and Kasai, 1994)
Go without ko, with bounded gamespolynomialPSPACE-hard (Lichtenstein and Sipser, 1980)
Checkerscan be exponentialEXP-complete (Robson, 1984)
Chesscan be exponentialEXP-complete (Fraenkel and Lichtenstein, 1981)
Go with the Japanese ko rulecan be exponentialEXP-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 ∃\exists) and PSPACE (a polynomial number of alternations) is an intermediate staircase: a fixed number of alternations.

Σ1p=NP\Sigma_1^p = \mathsf{NP}, Π1p=\Pi_1^p = coNP, and by convention Σ0p=Π0p=P\Sigma_0^p = \Pi_0^p = \mathsf{P}. Adding a dummy quantifier shows Σkp∪Πkp⊆Σk+1p∩Πk+1p\Sigma_k^p \cup \Pi_k^p \subseteq \Sigma_{k+1}^p \cap \Pi_{k+1}^p. An equivalent oracle characterization: Σk+1p=NPΣkp\Sigma_{k+1}^p = \mathsf{NP}^{\Sigma_k^p}, an NP machine allowed free queries to a problem at the previous level. And since TQBF with kk alternations is in PSPACE, PH⊆PSPACE\mathsf{PH} \subseteq \mathsf{PSPACE}.

Are there natural problems at the second level? Yes, and very close to engineering. Circuit minimization: given a circuit CC and number kk, does an equivalent circuit of size ≤k\le k to CC exist? It is written ∃C′ ∀x  [∣C′∣≤k∧C′(x)=C(x)]\exists C'\, \forall x\; [\abs{C'} \le k \wedge C'(x) = C(x)], so it is in Σ2p\Sigma_2^p. Guessing C′C' is not enough for NP, because checking equivalence is coNP-complete. The version for formulas in disjunctive normal form, MIN-DNF, is Σ2p\Sigma_2^p-complete (Umans, 2001). Its complement, “is this circuit minimal?”, is ∀C′\forall C' small ∃x\exists x on which they differ: Π2p\Pi_2^p.

Proof

Take k=1k = 1; the general case is identical one level up. Suppose NP=coNP\mathsf{NP} = \mathsf{coNP} and let L∈Σ2pL \in \Sigma_2^p: x∈L  ⟺  ∃y ∀z  V(x,y,z)x \in L \iff \exists y\, \forall z\; V(x, y, z). Language L′={(x,y):∀z  V(x,y,z)}L' = \{(x, y) : \forall z\; V(x, y, z)\} is in coNP, hence in NP: there exists V′V' with (x,y)∈L′  ⟺  ∃w  V′(x,y,w)(x, y) \in L' \iff \exists w\; V'(x, y, w). Then x∈L  ⟺  ∃y ∃w  V′(x,y,w)x \in L \iff \exists y\, \exists w\; V'(x, y, w), and two consecutive ∃\exists are one on the pair (y,w)(y, w): L∈NPL \in \mathsf{NP}. Thus Σ2p=NP\Sigma_2^p = \mathsf{NP}, and by complement Π2p=coNP=NP\Pi_2^p = \mathsf{coNP} = \mathsf{NP}. By induction, the same argument absorbs each new quantifier and all levels are NP. If P=NP\mathsf{P} = \mathsf{NP}, since P is closed under complement, NP=coNP=P\mathsf{NP} = \mathsf{coNP} = \mathsf{P} 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 Σkp\Sigma_k^p, 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 xx, a string rr of uniform independent random bits.

Constants 1/21/2 and 2/32/3 are arbitrary, and here is the technical heart of randomness: amplification. In RP it is immediate: repeat kk times and accept if any accepts, leaving error 2−k2^{-k} without introducing false positives. In BPP one must vote.

Proof

Let XX be the number of erroneous runs, the sum of kk independent Bernoulli variables with means ≤1/2−δ\le 1/2 - \delta, so E[X]≤k(1/2−δ)\E[X] \le k(1/2 - \delta). The majority errs only if X≥k/2X \ge k/2 (counting ties as errors), that is, if X−E[X]≥kδX - \E[X] \ge k\delta. By Hoeffding’s inequality, P[X−E[X]≥kδ]≤e−2(kδ)2/k=e−2δ2k\Pr[X - \E[X] \ge k\delta] \le e^{-2(k\delta)^2/k} = e^{-2\delta^2 k}. To make it ≤2−q\le 2^{-q}, k≥qln⁡2/(2δ2)k \ge q\ln 2/(2\delta^2) suffices.

∎

With δ=1/6\delta = 1/6 (error 1/31/3), k≥18ln⁡(1/ε)k \ge 18\ln(1/\eps) repetitions suffice for error ε\eps: 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 1/δ21/\delta^2 is real.

Known inclusions

  • P⊆ZPP\mathsf{P} \subseteq \mathsf{ZPP} (do not use randomness), RP⊆BPP\mathsf{RP} \subseteq \mathsf{BPP} (error ≤1/2\le 1/2 amplified to ≤1/4\le 1/4) and RP⊆NP\mathsf{RP} \subseteq \mathsf{NP}: if x∈Lx \in L, some rr makes it accept, and that rr is a certificate verified by executing MM.
  • ZPP=RP∩coRP\mathsf{ZPP} = \mathsf{RP} \cap \mathsf{coRP}. 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.
  • BPP⊆Σ2p∩Π2p\mathsf{BPP} \subseteq \Sigma_2^p \cap \Pi_2^p (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 ∃∀\exists\forall formula.

The most important example of RP and coRP is polynomial identity testing: given an arithmetic circuit computing a polynomial pp of degree dd, is p≡0p \equiv 0? By the Schwartz–Zippel lemma, if p≢0p \not\equiv 0 and evaluated at a random point of SnS^n, P[p(r)=0]≤d/∣S∣\Pr[p(\vb{r}) = 0] \le d/\abs{S}. Thus “p≡0p \equiv 0” 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 nn is less than 2−n2^{-n}; it uses m(n)m(n) random bits with mm polynomial. Fix nn. For each xx of length nn, the fraction of seeds r∈{0,1}mr \in \{0,1\}^m erring on xx is below 2−n2^{-n}. By the union bound, the fraction of seeds erring on any of the 2n2^n inputs is less than 2n⋅2−n=12^n \cdot 2^{-n} = 1. Thus a seed rn∗r_n^* exists that is correct for all inputs of length nn. Circuit CnC_n is the machine with rn∗r_n^* hardwired; a machine of time tt becomes a circuit of size O(t2)\bigO(t^2) with the same Cook–Levin tableau construction.

∎

The proof does not say how to find rn∗r_n^* 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 E=TIME(2O(n))\mathsf{E} = \mathsf{TIME}(2^{\bigO(n)}) needs circuits of size 2Ω(n)2^{\Omega(n)}, then BPP=P\mathsf{BPP} = \mathsf{P}. 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 P=NP\mathsf{P} = \mathsf{NP}.

Determinant versus permanent

For a matrix A∈Rn×n\mat{A} \in \R^{n\times n}, the determinant and permanent are

det⁡A=∑σ∈Snsgn⁡(σ)∏i=1naiσ(i),perm⁡A=∑σ∈Sn∏i=1naiσ(i).\det\mat{A} = \sum_{\sigma \in S_n} \operatorname{sgn}(\sigma) \prod_{i=1}^n a_{i\sigma(i)}, \qquad \operatorname{perm}\mat{A} = \sum_{\sigma \in S_n} \prod_{i=1}^n a_{i\sigma(i)}.

They differ only by sign. If A\mat{A} 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 perm⁡A\operatorname{perm}\mat{A} counts them. The determinant is computed in O(n3)\bigO(n^3) 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.

InteractiveCounting versus deciding
c1c2c3c4c5f1f2f3f4f5
rowscolumnsf1f2f3f4f5c1c2c3c4c5
  • edge (entry 1)
  • current perfect matching
σ 1 of 8
σ=(1,2,3,4,5)\sigma = (1, 2, 3, 4, 5): row ii with column σ(i)\sigma(i). Sign +1+1: add +1 to the determinant and +1 to the permanent.
There are 8 perfect matchings, but det⁡=0\det = 0: permutation signs cancel. The determinant costs O(n3)\bigO(n^3) and the permanent, as far as is known, exponential time.
Graph
5
Perfect matching exists?yes
Search steps (decision)15
Permanent (Ryser)8
Determinant0
Signed sum (1 of 8)1
Products with Ryser160
Products by brute force600
Mean det⁡(A∘S)2\det(\mat{A}\circ\mat{S})^2no samples
The matrix is the biadjacency matrix of a bipartite graph: click cells to change edges. Traverse perfect matchings one by one and see their signs: the permanent adds +1+1 for each, the determinant adds its sign. In the 5×55 \times 5 band there are 8 matchings and determinant 0: how many have each sign? Sample random signs: the mean of det⁡(A∘S)2\det(\mat{A}\circ\mat{S})^2 approaches the permanent, but what is its standard deviation?

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: Fn+1F_{n+1}. Each swap is a transposition with sign −1-1, so the determinant sums ±1\pm 1 according to the parity of the number of swaps and nearly cancels. In the complete graph with n≥2n \ge 2, the permanent is n!n! and determinant 0.

Proof

Expanding the product, ∏i∑j∈Saij=∑f∏iaif(i)\prod_i \sum_{j \in S} a_{ij} = \sum_{f} \prod_i a_{i f(i)}, where ff ranges over all functions from {1,…,n}\{1, \dots, n\} to SS. Write w(f)=∏iaif(i)w(f) = \prod_i a_{if(i)}. The permanent sums w(f)w(f) over bijections, exactly the functions from {1,…,n}\{1,\dots,n\} to itself whose image is the whole set. By inclusion–exclusion over columns outside the image, the sum over surjective functions is ∑S(−1)n−∣S∣∑f:[n]→Sw(f)\sum_{S} (-1)^{n - \abs{S}} \sum_{f : [n] \to S} w(f): a function with image TT appears in all S⊇TS \supseteq T, with total weight ∑S⊇T(−1)n−∣S∣=(1−1)n−∣T∣\sum_{S \supseteq T} (-1)^{n - \abs{S}} = (1 - 1)^{n - \abs{T}}, which is 1 if T=[n]T = [n] and 0 otherwise.

∎

Evaluating the formula as written costs O(2nn2)\bigO(2^n n^2). If subsets are traversed in Gray code, each differs from its predecessor in one column, the nn row sums update in O(n)\bigO(n), and total cost drops to O(2nn)\bigO(2^n n): compared with n⋅n!n \cdot n! for brute force, for n=20n = 20 that is about 2×1072\times 10^7 products versus 5×10195\times 10^{19}. It remains exponential and nothing substantially better is known.

How far counting reaches

Counting is powerful. Toda’s theorem (1991) says PH⊆P#P\mathsf{PH} \subseteq \mathsf{P}^{\#\mathsf{P}}: a single query to a counting oracle suffices to solve any problem at any level of the polynomial hierarchy. Above that, P#P⊆PSPACE\mathsf{P}^{\#\mathsf{P}} \subseteq \mathsf{PSPACE}, 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 1±ε1 \pm \eps 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 ∣det⁡∣\abs{\det} equals the permanent.

The Godsil–Gutman estimator in the figure illustrates why approximation is not trivial. If S\mat{S} has independent uniform signs ±1\pm 1, E[det⁡(A∘S)2]=perm⁡A\E[\det(\mat{A}\circ\mat{S})^2] = \operatorname{perm}\mat{A} for A\mat{A} 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 nn, requiring exponentially many samples.

Circuits: P/poly and barriers

A Boolean circuit with nn inputs computes a Boolean function {0,1}n→{0,1}\{0,1\}^n \to \{0,1\}. 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 1n1^n such that machine number nn halts on an empty tape, because for every nn the circuit is the appropriate constant. But it also makes it useful for separation: since P⊆P/poly\mathsf{P} \subseteq \mathsf{P/poly} (a machine of time tt is a circuit of size O(t2)\bigO(t^2)), proving NP⊈P/poly\mathsf{NP} \not\subseteq \mathsf{P/poly} would prove P≠NP\mathsf{P} \neq \mathsf{NP}. 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, PH=Σ2p\mathsf{PH} = \Sigma_2^p.

Almost all functions are hard

Proof

There are 22n2^{2^n} functions. A circuit with ss gates is described by choosing, for each gate, one of 16 binary operations and its two inputs among n+sn + s possible sources, then the output gate: at most s (16(n+s)2)ss\,(16(n+s)^2)^s circuits. With s=2n/(10n)s = 2^n/(10n), log⁡2\log_2 of that number is s (4+2log⁡2(n+s))+log⁡2s≤s⋅2.1n≈2n/4.8s\,(4 + 2\log_2(n + s)) + \log_2 s \le s \cdot 2.1n \approx 2^n/4.8 for large nn. Circuits of that size compute at most 22n/4.82^{2^n/4.8} functions, a fraction 22n/4.8−2n2^{2^n/4.8 - 2^n} tending to 0 of the 22n2^{2^n}.

∎

This is a pure counting argument, like that for Kolmogorov-incompressible strings: there are more functions than small circuits. For n=20n = 20 the same count without approximations guarantees functions needing more than 30 000 gates, and Lupanov (1958) proved (1+o(1)) 2n/n(1 + o(1))\,2^n/n 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 3n3n gates (Blum, 1984), improved since only in the coefficient. There is a chasm between 3n3n 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 AC0\mathsf{AC}^0; 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.

  1. Relativization (Baker, Gill and Solovay, 1975). Simulation and diagonalization proofs work the same with any oracle, and some oracles give P=NP\mathsf{P} = \mathsf{NP} while others do not. Diagonalization alone does not suffice.
  2. 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.
  3. Algebrization (Aaronson and Wigderson, 2009). Algebraic techniques that evade relativization (those of IP=PSPACE\mathsf{IP} = \mathsf{PSPACE}) also do not suffice: they relativize relative to algebraic extensions of the oracles.

The barriers do not say P≠NP\mathsf{P} \neq \mathsf{NP} is unprovable; they say a proof will need ideas we do not currently have.

The complete map

Put everything together:

L⊆NL⊆P⊆ZPP⊆RP⊆NP⊆Σ2p⊆PH⊆P#P⊆PSPACE⊆EXP,\mathsf{L} \subseteq \mathsf{NL} \subseteq \mathsf{P} \subseteq \mathsf{ZPP} \subseteq \mathsf{RP} \subseteq \mathsf{NP} \subseteq \Sigma_2^p \subseteq \mathsf{PH} \subseteq \mathsf{P}^{\#\mathsf{P}} \subseteq \mathsf{PSPACE} \subseteq \mathsf{EXP},

with RP⊆BPP⊆Σ2p∩Π2p\mathsf{RP} \subseteq \mathsf{BPP} \subseteq \Sigma_2^p \cap \Pi_2^p in parallel. Known strict separations, all by diagonalization: NL⊊PSPACE\mathsf{NL} \subsetneq \mathsf{PSPACE}, P⊊EXP\mathsf{P} \subsetneq \mathsf{EXP}, NP⊊NEXP\mathsf{NP} \subsetneq \mathsf{NEXP} and PSPACE⊊EXPSPACE\mathsf{PSPACE} \subsetneq \mathsf{EXPSPACE}. Everything else is open. A practical way to use the map is to place each problem in the most precise known class:

ProblemMost precise known class
Undirected graph reachabilityL (Reingold)
Directed graph reachability, 2-SATNL-complete
Circuit value, linear programmingP-complete
Polynomial identity testingcoRP; not known to be in P
SAT, clique, Hamiltonian cycleNP-complete
Tautologies (TAUT)coNP-complete
MIN-DNF, circuit minimizationΣ2p\Sigma_2^p (MIN-DNF is Σ2p\Sigma_2^p-complete)
Count assignments, 0/1 permanent, count matchings#P-complete
TQBF, geography, Hex, polynomial-length gamesPSPACE-complete
Generalized chess, checkers or Go with unbounded gamesEXP-complete

Implementation from scratch

First, Savitch recursion as written, instrumented to count calls and maximum stack depth, on directed paths of nn vertices. Each query is made in both directions: forward the destination is reachable, backward it is not.

[ ]Savitch recursion, measuredBrowser
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 k+1k + 1, while calls rise from dozens to nearly 10510^5 as vertices increase from 4 to 16, below bound (2n)k(2n)^k but growing at the same rate. At these sizes breadth-first search uses fewer bits than Savitch (nn versus 3(k+1)log⁡n3(k+1)\log n); Savitch’s advantage is asymptotic, and by the figure’s count begins around N=256N = 256.

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 ∃\exists stops upon finding a true child and a ∀\forall upon finding a false one.

[ ]TQBF and generalized geographyBrowser
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 2n+1−12^{n+1} - 1 and time quadruples every two variables; depth never exceeds nn. 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 2−402^{-40}? The exact binomial tail is computed using the incomplete beta function, P[Bin⁡(k,p)≥m]=Ip(m,k−m+1)\Pr[\operatorname{Bin}(k, p) \ge m] = I_p(m, k - m + 1). Three numbers are compared: Hoeffding’s bound ln⁡(1/ε)/(2δ2)\ln(1/\eps)/(2\delta^2), Chernoff’s using Kullback–Leibler divergence ln⁡(1/ε)/KL⁡(1/2 ∥ p)\ln(1/\eps)/\KL(1/2 \,\|\, p), and the exact minimum odd kk.

[ ]Amplification: bounds and exact valueBrowser
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 1/δ21/\delta^2: moving from δ=0.1\delta = 0.1 to δ=0.01\delta = 0.01 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.

[ ]Decide with Hopcroft–Karp, count with RyserBrowser
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 nn grows by 2, as predicted by 2nn2^n n, 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 n=2000n = 2000, Ryser counting would require about 220002^{2000} 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.

[ ]Estimate the permanent with random signsBrowser
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 12×1212\times 12 band has F13=233F_{13} = 233 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 5×1045 \times 10^4 and 3.4×1053.4 \times 10^5 samples (the square of that ratio times 10410^4) even on these small matrices, and for bad families the ratio grows exponentially with nn.

With libraries

TaskToolComment
Decide perfect matchingscipy.sparse.csgraph.maximum_bipartite_matchingHopcroft–Karp on sparse matrices
Exact permanentsympy.Matrix.per()exact on integers; exponential like Ryser
Count models of a formulasharpSAT, d4, Ganakknowledge compilers and exact counters; exploit structure
Solve QBFDepQBF, CAQEQBF solvers with clause learning
[ ]The same calculations with librariesBrowser
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

QuizThe most precise class
Which of these assignments of a problem to its most precise known class are correct?

More than one answer may be correct.

QuizWhat is known to be strict
Which inclusions are known to be strict?

More than one answer may be correct.

QuizIs being right more than half the time enough?
A polynomial-time randomized algorithm decides a problem correctly with probability at least 1/2+2−n1/2 + 2^{-n} on each input of length nn. What can be concluded?
QuizMinimizing a circuit
Given a circuit CC and integer kk, does a circuit of size at most kk computing the same function as CC exist? What is the best known upper bound?
NumericRepetitions for an error of 2⁻¹⁰⁰
A BPP algorithm errs with probability 1/31/3. Using Hoeffding's bound, P[la mayorıˊa de k votos falla]≤e−2δ2k\Pr[\text{la mayoría de } k \text{ votos falla}] \le e^{-2\delta^2 k} with δ=1/2−1/3\delta = 1/2 - 1/3, what is the smallest kk guaranteeing error at most 2−1002^{-100}?
NumericSavitch's stack
A configuration graph has N=240N = 2^{40} configurations, each encoded with 40 bits. To decide whether one is reachable from another, call \textscReach(u,v,40)\textsc{Reach}(u, v, 40). Each recursion level stores uu, vv and midpoint ww (ignore counter kk). How many bits does the full stack occupy?
NumericMatchings of a band
The 10×1010 \times 10 matrix has ones on the main diagonal and its two neighbors, and zeros elsewhere. How many perfect matchings does its bipartite graph have, i.e. what is its permanent?
ProofSavitch's theorem
Prove: If s(n)≥log⁡ns(n) \ge \log n is space-constructible, then NSPACE(s(n))⊆SPACE(s(n)2)\mathsf{NSPACE}(s(n)) \subseteq \mathsf{SPACE}(s(n)^2).
0
Let MM be a nondeterministic machine deciding LL in space s(n)s(n).

Step 1 of 4. To what problem do you reduce acceptance by xx?

ProofZPP is RP intersect coRP
Prove: ZPP=RP∩coRP\mathsf{ZPP} = \mathsf{RP} \cap \mathsf{coRP}.
0
Recall: a ZPP algorithm is always correct and has polynomial expected time; an RP algorithm has polynomial worst-case time, never accepts when the answer is ‘no’ and accepts with probability ≥1/2\ge 1/2 when it is ‘yes’.

Step 1 of 4. Let ZZ be a ZPP algorithm for LL with expected time ≤p(n)\le p(n). How do you obtain an RP algorithm?

CodeRyser's formula
Implement permanente(A) using Ryser's formula, perm⁡A=∑S(−1)n−∣S∣∏i∑j∈Saij\operatorname{perm}\mat{A} = \sum_{S} (-1)^{n - \abs{S}} \prod_i \sum_{j \in S} a_{ij}, in O(2nn)\bigO(2^n n) operations (Gray code) or at least O(2nn2)\bigO(2^n n^2). A is a list of lists of integers of size n×nn \times n with n≥1n \ge 1. Do not use itertools.permutations: the tests compare with the definition on small matrices and require a matrix of 10×1010 \times 10 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 total
Shift+Enter to run

Summary

Key idea
Beyond NP, difficulty is measured with other resources and questions: memory (L, NL, PSPACE), alternating quantifiers (PH and PSPACE games), randomness (RP, ZPP, BPP) and counting (#P); all unconditional separations in the map come from diagonalization, so almost all of it remains open.
  • Hierarchy theorems, proved by diagonalization with a clock, guarantee that more time or space decides more: P⊊EXP\mathsf{P} \subsetneq \mathsf{EXP} and NL⊊PSPACE\mathsf{NL} \subsetneq \mathsf{PSPACE}. Diagonalization relativizes and therefore does not suffice for P versus NP.
  • The configuration graph connects space and time: 2O(s)2^{\bigO(s)} configurations yield NSPACE(s)⊆TIME(2O(s))\mathsf{NSPACE}(s) \subseteq \mathsf{TIME}(2^{\bigO(s)}). Savitch tries every midpoint and reuses the stack: NSPACE(s)⊆SPACE(s2)\mathsf{NSPACE}(s) \subseteq \mathsf{SPACE}(s^2) and PSPACE=NPSPACE\mathsf{PSPACE} = \mathsf{NPSPACE}. Immerman and Szelepcsényi: NL=coNL\mathsf{NL} = \mathsf{coNL}.
  • 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 ∃\exists and ∀\forall; circuit minimization lives in Σ2p\Sigma_2^p, and if P=NP\mathsf{P} = \mathsf{NP} 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; ZPP=RP∩coRP\mathsf{ZPP} = \mathsf{RP} \cap \mathsf{coRP}, BPP⊆P/poly∩Σ2p\mathsf{BPP} \subseteq \mathsf{P/poly} \cap \Sigma_2^p, and BPP=P\mathsf{BPP} = \mathsf{P} 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 O(2nn)\bigO(2^n n). The entire polynomial hierarchy fits in P#P\mathsf{P}^{\#\mathsf{P}}.
  • Almost all functions require exponential circuits (Shannon), but we cannot identify any NP function needing more than about 3n3n gates; the barriers of relativization, natural proofs and algebrization explain part of the difficulty.