Module contents
Lesson 27 of 33Core 115 min

P, NP and the Cook-Levin theorem

NP-completeness theory explains why thousands of important problems resist efficient solution. Define decision, search and optimization problems, P and NP through verifiers, polynomial reductions and NP-completeness. Prove Cook–Levin by encoding a Turing machine execution as a formula, and study coNP and the self-reducibility converting decision into search.

After this lesson you can

  • Formulate a problem as a decision language and relate it to search and optimization versions.
  • Prove a problem belongs to NP by giving a certificate and polynomial verifier.
  • Construct polynomial reductions and use them in the correct direction.
  • Prove Cook–Levin with the configuration-tableau construction.
  • Explain coNP, the NP = coNP question and obtaining solutions from a decision oracle.

Before you start

Motivation: finding versus checking

You have spent twenty-six lessons designing algorithms: sorting, matching, routing flow, finding paths. This lesson asks the opposite: how can we prove that an efficient algorithm for a problem will not be found? Nobody knows how to prove a natural problem requires superpolynomial time, but something almost as useful is possible: prove it is as hard as thousands of others resisting decades of attempts, so an efficient algorithm for it would solve them all. This guides work toward approximations, special cases, small parameters or a SAT solver instead of searching endlessly for a perfect exact algorithm.

Three real situations end up in the same family:

  • Traveling salesperson. A courier visits 20 cities and returns to the depot. There are 19!/2≈6.1×101619!/2 \approx 6.1\times 10^{16} tours; at 10910^9 tours per second, checking all takes about two years. Bellman and Held–Karp dynamic programming (1962) reduces this to O(n22n)\bigO(n^2 2^n), a huge improvement still exponential. No polynomial algorithm is known.
  • Shift scheduling. Is there an assignment of people to shifts respecting contracts, holidays, minimum rest and preferences? This is constraint satisfaction. With a few dozen people, the assignment space is astronomical.
  • Exact program analysis. “Is there an input causing this assertion to fail within at most kk execution steps?” translates into a Boolean formula satisfiable exactly when such an input exists. This is precisely the idea proved below and used by bounded model checkers (see SAT in practice and SMT in the classical AI module).

All three share an asymmetry. Checking a proposal is easy: given a tour, sum 20 distances; given a schedule, check rules; given an input, execute the program. Finding the proposal seems to require exploring an exponential space. Whether this difference is real or merely lack of ingenuity is the P\mathsf{P} versus NP\mathsf{NP} question, one of the Clay Institute’s seven Millennium Problems, still open.

Explore the asymmetry before formalizing it. Choose a problem, propose a certificate and see checking cost; then let brute force search and increase size.

InteractiveVerify versus solve
Subset sum: choose numbers that sum to the target
15041438383937114042722390519093925282514233590marked sum = 15469target = 13965
✗ the sum is 15469, not 13965. Verification costs 13 steps (add the nn marked numbers and compare).
100105101010151020102030405060size (numbers); gray area: curve only, no run
  • verify a certificate
  • brute force, worst case
  • your measured runs
Problem
12
Your certificateinvalid
Steps to verify13
Candidates tried0 of 4 096
Brute-force stepsnot run
Worst case5.3·10^4 steps
At 10910^9 steps/s at size 602229 years
Three problems with planted solutions. Click chips, vertices or cells to construct a certificate: the verifier immediately judges it and counts steps (each instance begins with a nearly correct certificate containing one error). ‘Solve by brute force’ actually traverses candidates in order until one is valid and counts them. The logarithmic plot compares verification cost (a line almost on the axis) with brute-force worst case (an exponential); gray is the curve beyond what can be run. Increase size one by one and observe the candidate-count multiplier. Change problem: which grows fastest? Use ‘Another case’ to see how candidates tried vary across instances while worst case does not.

Three observations about what you just saw, and a caveat.

  1. Verification is one pass through the certificate. Subset sum takes n+1n + 1 steps, coloring one check per edge, and Sudoku one read per group. This grows as a small polynomial of input size.
  2. Brute force multiplies by a constant per unit of size: 2n2^n subsets, 3n3^n colorings, 4k4^k fillings of kk empty cells. Each extra number, vertex or cell doubles, triples or quadruples work.
  3. Candidates tried vary greatly depending on where the first solution lies in traversal order. Worst case does not.

The caveat: brute force is not the best known algorithm. Subset sum takes O(2n/2)\bigO(2^{n/2}) with meet-in-the-middle (Horowitz and Sahni, 1974), 3-coloring O(1.3289n)\bigO(1.3289^n) (Beigel and Eppstein, 2005), and 9×99\times 9 Sudoku solves in milliseconds with backtracking and propagation. But all known algorithms for these problems remain exponential in the worst case, and for this lesson’s problems there is a structural reason, not just lack of ingenuity: they are equivalent to one another.

To turn intuition into mathematics fix three things: what a problem is, what efficient means and what checking means. Then compare problem difficulty with reductions and find the hardest efficiently verifiable problem (Cook and Levin).

Decision, search and optimization problems

Almost every computational problem has three versions. For clique, given a graph GG and seeking pairwise adjacent vertices:

  • Decision. Given GG and kk, does GG have a clique of size at least kk? Answer yes or no.
  • Search. Given GG and kk, return a clique of size at least kk if one exists.
  • Optimization. Given GG, return a maximum clique.
ProblemDecisionSearchOptimization
Traveling salespersonis there a tour of length ≤L\le L?the tourshortest tour
Satisfiabilityis there an assignment satisfying φ\varphi?the assignmentone satisfying most clauses (MAX-SAT)
Subset sumdoes some subset sum to tt?the subsetclosest to tt without exceeding it
Coloringcan it be colored with kk colors?the coloringminimum color count

Complexity theory usually formulates the first version because it is simplest: a function from {0,1}∗\{0,1\}^* to {sıˊ,no}\{\text{sí}, \text{no}\}.

The rest concerns languages; do we lose anything ignoring search and optimization? Almost nothing, proved in two halves: optimization reduces to decision by binary-searching a threshold (now), and search reduces to decision by testing variables one by one (at the end).

Proof

Maintain interval [a,c][a, c] containing OPT(x)\mathrm{OPT}(x), initially [0,2q][0, 2^q]. While a<ca < c, ask DD about b=⌈(a+c)/2⌉b = \lceil (a + c)/2 \rceil. If yes, OPT(x)≥b\mathrm{OPT}(x) \ge b and move to [b,c][b, c]; if no, OPT(x)≤b−1\mathrm{OPT}(x) \le b - 1 and move to [a,b−1][a, b - 1]. Either way integer count N=c−a+1N = c - a + 1 becomes at most ⌈N/2⌉\lceil N/2 \rceil. Starting from N=2q+1N = 2^q + 1, after q+1q + 1 steps N=1N = 1 remains, i.e. a=c=OPT(x)a = c = \mathrm{OPT}(x). ■\blacksquare

∎

For maximum clique on 100 vertices, OPT\mathrm{OPT} lies between 1 and 100 and ⌈log⁡2100⌉=7\lceil \log_2 100 \rceil = 7 queries suffice. The important condition is “integer bounded by 2polinomio2^{\text{polinomio}}”: in traveling salesperson, optimum sums distances and has as many bits as distances themselves, so binary search makes polynomially many queries even with exponentially many tours. Implement it in the second code-section cell.

Size means bit count

“Polynomial in input size” matters only if size is measured correctly. An encoding is reasonable if two reasonable encodings of one instance have polynomially related sizes: an adjacency matrix takes n2n^2 bits and a vertex–edge list O((n+m)log⁡n)\bigO((n + m) \log n), and since m≤n2m \le n^2 sizes are polynomially related; either works. The classic trap is numbers. Writing NN in binary takes log⁡2N\log_2 N bits; in unary, NN. An O(N)\bigO(N)-step algorithm is linear for unary input and exponential for binary.

Familiar examples: knapsack and subset-sum dynamic programming (pseudopolynomial algorithms) takes O(nt)\bigO(nt) for nn numbers and target tt, but tt is exponential in its bit count: with 64-bit tt the table has order 264n2^{64}n cells. It is pseudopolynomial because it is polynomial in numeric values, not their sizes. And testing primality by dividing NN by every integer up to N\sqrt{N} takes N=2b/2\sqrt{N} = 2^{b/2} steps, with bb the bit count of NN.

Class P

Choosing polynomial rather than, say, O(n2)\bigO(n^2) has technical and practical reasons.

Closure. Polynomials are closed under sum, product and composition. Running a polynomial algorithm polynomially many times, or feeding it another’s output, stays polynomial. Without this property there would be no reduction theory.

Model robustness. A single-tape Turing machine simulates a multitape one with quadratic overhead, and a RAM with logarithmic operation cost with polynomial overhead; thus P\mathsf{P} is unchanged across reasonable models. This is the resource version of the Church–Turing thesis (called the strong thesis, viewed cautiously due to quantum computing: BQP\mathsf{BQP} is not known to lie in P\mathsf{P}). This robustness lets the lesson say “polynomial time” without specifying a machine.

A practical warning: P\mathsf{P} does not mean fast. An n100n^{100} algorithm is in P\mathsf{P} and useless; an 1.0001n1.0001^n algorithm is outside it and excellent for n≤104n \le 10^4. The thesis says the polynomial–exponential boundary best survives model changes; experience says that, with few exceptions, problems solvable in P\mathsf{P} eventually acquire small-exponent algorithms.

You have seen many members of P\mathsf{P}: shortest paths, minimum spanning trees, maximum flow and matching. Also 2-SAT (strongly connected components, as in DFS), linear programming (Khachiyan, 1979) and, since 2002, primality (Agrawal, Kayal and Saxena).

Class NP

Look again at the first figure’s verifier: read a certificate and decide. That is the definition.

Notice two asymmetries. A short certificate is required only for positive instances: yes can be shown with a short proof, no need not be. And the verifier need not know how ww was found; the definition says nothing about finding difficulty.

ProblemCertificateVerifier checks
SATa variable assignmentevery clause has a true literal
Clique of size kkthe kk verticeseach pair is an edge
Hamiltonian cyclea permutation of verticesconsecutive pairs and last with first are edges
Subset sumselected indicestheir values sum to tt
3-coloringone color per vertexno edge is monochromatic
Compositea divisor dd with 1<d<N1 < d < Nd∣Nd \mid N
Sudokudigits for empty cellseach group contains digits without repetition

The name comes from another equivalent definition used by Cook and Karp. A nondeterministic Turing machine may choose among transitions at each step; it accepts if any computation branch accepts, and its time is that of the longest branch.

Proof

(⇐\Leftarrow) Given verifier VV and polynomial pp, nondeterministic machine NN writes an p(∣x∣)p(\abs{x})-bit string ww bit by bit (two choices per bit, p(∣x∣)p(\abs{x}) steps), then executes V(x,w)V(x, w). A branch accepts iff some ww has V(x,w)=1V(x, w) = 1, and time is polynomial.

(⇒\Rightarrow) Let NN be nondeterministic with time q(∣x∣)q(\abs{x}). Assume it chooses at most two transitions per step (a choice among bb splits into ⌈log⁡2b⌉\lceil \log_2 b \rceil binary choices). A certificate is the q(∣x∣)q(\abs{x}) binary choices of a branch. The verifier simulates NN using those choices and accepts if the branch ends in an accepting state. It takes O(q(∣x∣))\bigO(q(\abs{x})) steps of NN, and NN accepts xx iff some choice sequence leads to acceptance. ■\blacksquare

∎

The proof shows “nondeterministic” and “certificate” are the same idea in two disguises: nondeterminism guesses the certificate, and choosing an accepting branch is the certificate. It also explains the name: NP\mathsf{NP} is nondeterministic polynomial time, not “non-polynomial.”

Proof

P⊆NP\mathsf{P} \subseteq \mathsf{NP}: if L∈PL \in \mathsf{P}, verifier V(x,w)V(x, w) ignores ww and runs the algorithm deciding LL on xx. NP⊆EXP\mathsf{NP} \subseteq \mathsf{EXP}: given the verifier and pp, enumerate the 2p(∣x∣)+1−12^{p(\abs{x}) + 1} - 1 possible certificates and run V(x,w)V(x, w) on each; accept if any accepts. This is 2O(p(n))2^{\bigO(p(n))} polynomial-algorithm executions. ■\blacksquare

∎

The time hierarchy theorem (Hartmanis and Stearns, 1965) shows P≠EXP\mathsf{P} \neq \mathsf{EXP}, so at least one of the two inclusions is strict. Nobody knows which. P=?NP\mathsf{P} \overset{?}{=} \mathsf{NP} asks, fundamentally, whether finding is essentially as easy as checking.

Polynomial reductions

How compare two problems’ difficulty without knowing how to solve either? Transform one into the other. If every AA instance can be converted in polynomial time into a BB instance with the same answer, any way to solve BB solves AA.

Reductions operate in one direction, easy to reverse accidentally.

Proof

Prove (3); parts (1) and (2) are a final guided exercise. Let VBV_B verify BB and ff reduce AA to BB. A verifier for AA receives (x,w)(x, w), computes f(x)f(x) and runs VB(f(x),w)V_B(f(x), w). Correctness follows from x∈A  ⟺  f(x)∈B  ⟺  ∃w  VB(f(x),w)=1x \in A \iff f(x) \in B \iff \exists w\; V_B(f(x), w) = 1. It is polynomial because f(x)f(x) is polynomial-time and, as a machine writes at most one symbol per step, ∣f(x)∣\abs{f(x)} is polynomial in ∣x∣\abs{x}; certificate ww remains polynomial in ∣f(x)∣\abs{f(x)} and hence ∣x∣\abs{x}. ■\blacksquare

∎

The key is the contrapositive of (2): reduction A≤pBA \le_p B transfers hardness from AA to BB, and easiness from BB to AA. Never the reverse. To prove a new problem hard, reduce a known hard problem to it.

InteractiveReduction direction
All NPthe classMatchingin PMax flowin P2-SATin PSATNP-complete3-SATNP-hard (mark)Independent setNP-completeCliqueNP-completeVertex coverNP-complete3-coloringNP-completeHamiltonianNP-completeTSPNP-completeSubset sumNP-completePartitionNP-complete
  • hard by consequence (travels with arrow)
  • easy by consequence (travels against arrow)
  • invalid conclusion (backward reasoning)
Mark for “3-SAT”
Direction of reasoning
Marked problems1
Hard by consequence10 of 14
Easy by consequence0 of 14
Arrow A→BA \to BA reduces to B
Each arrow A→BA \to B is polynomial reduction A≤pBA \le_p B (two-headed arrows mean one reduction each way). Click a problem to select it, then again to cycle through unmarked, ‘polynomial algorithm’ (green) and ‘NP-hard’ (red), and see propagation: hardness travels along arrows, easiness against them. Start with the 3-SAT scenario and see what is marked. Then choose ‘Someone solves clique in polynomial time’: why do even problems unconnected by arrows become easy? Finally enable ‘Reversed’ in the 3-SAT scenario: reversed reasoning marks 2-SAT hard even though it is in P, exposing the absurd conclusion.

Two qualifications. First, a more permissive Cook or Turing reduction: A≤pTBA \le_p^T B if a polynomial algorithm for AA may make polynomially many queries to a BB oracle and use answers arbitrarily, including negating them. Every Karp reduction is a Cook reduction (one query, unchanged answer). Cook formulated his 1971 result with oracle reductions; the Karp-reduction statement and 21-problem list are Karp (1972), while Levin proved it independently in the Soviet Union (published 1973). This distinction matters for coNP\mathsf{coNP}: under Cook reduction SAT’s complement reduces to SAT (ask and negate), but that does not put it in NP\mathsf{NP}, and a Karp reduction cannot negate the answer. Second, valid reductions require both implications: positive AA instances must yield positive BB instances and negative must yield negative.

NP-hardness and NP-completeness

NP-complete problems are the hardest in NP\mathsf{NP}: every verifiable problem reduces to them. The halting problem is NP-hard (every language of NP\mathsf{NP} reduces to it) but not NP-complete because it is undecidable and thus outside NP\mathsf{NP}. Someone “having a reduction from AA to BB” says something about BB only if AA is hard.

Proof

Let BB be NP-complete and B∈PB \in \mathsf{P}. For any A∈NPA \in \mathsf{NP}, A≤pBA \le_p B, and by part (2) of the previous theorem, A∈PA \in \mathsf{P}. Thus NP⊆P\mathsf{NP} \subseteq \mathsf{P}, and the other inclusion was already known. The second sentence is the contrapositive. ■\blacksquare

∎

This gives the practical recipe, developed in the next lesson. To show CC NP-complete:

  1. C∈NPC \in \mathsf{NP}: describe a polynomial-length certificate and polynomial verifier.
  2. Pick a problem AA already known NP-complete (or NP-hard).
  3. Construct polynomial-time function ff mapping AA instances to CC instances.
  4. Prove x∈A  ⟺  f(x)∈Cx \in A \iff f(x) \in C, both directions.

Step 2 works because reduction is transitive: if every NP\mathsf{NP} reduces to AA and A≤pCA \le_p C, every NP\mathsf{NP} reduces to CC. But the recipe needs a first NP-complete problem, requiring reduction of all NP\mathsf{NP} problems at once without knowing them. Cook and independently Levin achieved this.

The Cook–Levin theorem

SAT is in NP\mathsf{NP} immediately: the certificate is an assignment and evaluating CNF is linear in size. Hardness is difficult: for any L∈NPL \in \mathsf{NP}, construct in polynomial time from xx a CNF φx\varphi_x satisfiable iff x∈Lx \in L.

The idea is that a computation is a table and a table is correct iff each small fragment is correct. Take verifier VV for LL with time T=q(∣x∣)T = q(\abs{x}) and m=p(∣x∣)m = p(\abs{x})-bit certificates (padding with a marker makes lengths equal). One Boolean variable for each possible cell content in the configuration tableau, and clauses saying successive rows are legal VV steps and the certificate is the only free part.

The computation tableau

Fix VV as a deterministic single-tape Turing machine, tape infinite both ways, tape alphabet Γ\Gamma (blank ⊔\sqcup), states QQ (including q0q_0, accepting qYq_Y and rejecting qNq_N, both halting) and transition δ:(Q∖{qY,qN})×Γ→Q×Γ×{L,R}\delta : (Q \setminus \{q_Y, q_N\}) \times \Gamma \to Q \times \Gamma \times \{L, R\}. A configuration is tape content, head position and state, written as a row where each cell contains a symbol from Γ\Gamma or a head, a pair (q,a)∈Q×Γ(q, a) \in Q \times \Gamma meaning “head here, in state qq, reading aa.” Cell alphabet is S=Γ∪(Q×Γ)S = \Gamma \cup (Q \times \Gamma), and a row is a configuration if exactly one cell has a head. A halting configuration transitions to itself, so computation can extend to TT steps.

The tableau has T+1T + 1 rows (row ii is the configuration after ii steps) and W=2T+∣x∣+m+2W = 2T + \abs{x} + m + 2 columns: the head starts T+1T + 1 cells from the left edge and cannot leave the table in TT steps. Cells outside are treated as blanks.

The property enabling the construction is locality. With the head marked in its cell, a cell’s content at time i+1i + 1 depends only on the three cells above.

Proof

Define F(a,b,c)F(a, b, c) by cases. If b=(q,σ)b = (q, \sigma) is a nonhalting head, with δ(q,σ)=(q′,σ′,D)\delta(q, \sigma) = (q', \sigma', D), the head leaves that cell and writes σ′\sigma': F=σ′F = \sigma'. If b=(q,σ)b = (q, \sigma) halts, F=bF = b. If b∈Γb \in \Gamma and a=(q,σ)a = (q, \sigma) is a nonhalting head with δ(q,σ)=(q′,σ′,R)\delta(q, \sigma) = (q', \sigma', R), the head arrives at this cell: F=(q′,b)F = (q', b). If cc is a nonhalting head moving LL, the symmetric case gives F=(q′,b)F = (q', b). Otherwise the cell is unchanged: F=bF = b. One step changes only the head cell and one neighbor; these cases cover exactly those possibilities, so successor equals FF cell by cell. (FF values on triples with two heads are arbitrary because they never occur in a configuration.) ■\blacksquare

∎

Call the window of cell (i,j)(i, j), with i≥1i \ge 1, the 2×32 \times 3-cell block formed by the three above, (i−1,j−1),(i−1,j),(i−1,j+1)(i-1, j-1), (i-1, j), (i-1, j+1), and the central one below, (i,j)(i, j). It is legal if Ci,j=F(Ci−1,j−1,Ci−1,j,Ci−1,j+1)C_{i,j} = F(C_{i-1,j-1}, C_{i-1,j}, C_{i-1,j+1}). Fixing the upper row determines the lower (not conversely: two configurations can have the same successor), enabling the next figure: a tiny screen-sized machine accepting three-bit certificates without consecutive ones.

InteractiveCook–Levin tableau
0123456t = 0t = 1t = 2t = 3t = 4t = 51A0110B1101A101B101Y101Y
row 5
Certificates:
Window of cell (1,2)(1, 2). The three cells above determine what goes below: F(A⋅1, 0, 1)=B⋅0F(\mathtt{A}{\cdot}\mathtt{1},\ \mathtt{0},\ \mathtt{1}) = \mathtt{B}{\cdot}\mathtt{0}. The table has B⋅0\mathtt{B}{\cdot}\mathtt{0}: legal window. Its clause is satisfied: if the three cells above match, the cell below follows the rule:
¬x0,1,A⋅1∨¬x0,2,0∨¬x0,3,1∨x1,2,B⋅0\lnot x_{0,1,\mathtt{A}{\cdot}\mathtt{1}} \lor \lnot x_{0,2,\mathtt{0}} \lor \lnot x_{0,3,\mathtt{1}} \lor x_{1,2,\mathtt{B}{\cdot}\mathtt{0}}
  • A: previous symbol was not 1
  • B: previous symbol was 1
  • Y: accept
  • N: reject
  • selected 2×3 window
  • edited cell
Bit w1w_1 of the certificate
Bit w2w_2 of the certificate
Bit w3w_3 of the certificate
Illegal windows0 of 35
Start clausessatisfied
Acceptance clausesatisfied
Does it satisfy the formula?yes
Accepted certificates5 of 8
Variables xi,j,sx_{i,j,s}630
Total clauses91 085
A verifier with two working states (A and B) and halting states Y (accept) and N (reject), on a 3-bit certificate w1w2w3w_1 w_2 w_3 (accepts if there are no consecutive ones, i.e. marked vertices form an independent set of path 1-2-3). Each row is a configuration; the head is the colored cell with the state’s initial. Columns start at 0, as in code below. Play computation row by row. Click any cell from row 1 onward: its 2×32 \times 3 window is outlined, the FF rule applied to the three cells above is shown, and its constraining clause appears. Then corrupt the tableau with the content selector (e.g. change a row-2 cell): illegal windows are dashed red and the violated clause is shown. Change the certificate and watch rows rebuild. Chips below show verifier verdict for all 8 certificates; the formula has exactly one model per ✓.

The formula

Variables are xi,j,sx_{i,j,s} for 0≤i≤T0 \le i \le T, 1≤j≤W1 \le j \le W and s∈Ss \in S: “cell (i,j)(i, j) contains symbol ss.” There are (T+1)⋅W⋅∣S∣(T + 1) \cdot W \cdot \abs{S} variables, and since ∣S∣\abs{S} depends only on VV and T≥∣x∣+mT \ge \abs{x} + m can be taken (so W=O(T)W = \bigO(T)), there are O(T2)\bigO(T^2). Formula φx=φcelda∧φinicio∧φmov∧φacepta\varphi_x = \varphi_{\text{celda}} \wedge \varphi_{\text{inicio}} \wedge \varphi_{\text{mov}} \wedge \varphi_{\text{acepta}} has four parts.

Cells. Each cell has exactly one symbol:

φcelda=⋀i,j[(⋁s∈Sxi,j,s)∧⋀s≠s′(¬xi,j,s∨¬xi,j,s′)].\varphi_{\text{celda}} = \bigwedge_{i,j} \Big[ \Big( \bigvee_{s \in S} x_{i,j,s} \Big) \wedge \bigwedge_{s \neq s'} \big( \lnot x_{i,j,s} \lor \lnot x_{i,j,s'} \big) \Big].

Start. Row 0 is the initial configuration with input xx: blanks to the left, head in state q0q_0 on the first symbol of ⟨x,w⟩\langle x, w \rangle, fixed symbols of xx (one unit clause each), and in the mm certificate cells a free bit: one clause x0,j,0∨x0,j,1x_{0,j,0} \lor x_{0,j,1} per cell (the head cell, if on w1w_1, is x0,j,(q0,0)∨x0,j,(q0,1)x_{0,j,(q_0,0)} \lor x_{0,j,(q_0,1)}), with blanks to the right. Those mm cells are the formula’s only free variables: ∃w\exists w lives here.

Movement. For every cell (i,j)(i, j) with i≥1i \ge 1 and every triple (a,b,c)∈S3(a, b, c) \in S^3, a four-literal clause:

φmov=⋀i≥1, j ⋀(a,b,c)∈S3(¬xi−1,j−1,a∨¬xi−1,j,b∨¬xi−1,j+1,c∨xi,j,F(a,b,c)).\varphi_{\text{mov}} = \bigwedge_{i \ge 1,\, j} \ \bigwedge_{(a,b,c) \in S^3} \Big( \lnot x_{i-1,j-1,a} \lor \lnot x_{i-1,j,b} \lor \lnot x_{i-1,j+1,c} \lor x_{i,j,F(a,b,c)} \Big).

It says: if a,b,ca, b, c is above, below is what FF dictates. Together with φcelda\varphi_{\text{celda}} (exactly one symbol below), this means the window is legal. At boundary columns omit the literal for the nonexistent cell.

Acceptance. Computation ends accepting: φacepta=⋁j, a∈ΓxT,j,(qY,a)\varphi_{\text{acepta}} = \bigvee_{j,\, a \in \Gamma} x_{T,j,(q_Y, a)}, one clause.

The proof

Proof

SAT ∈NP\in \mathsf{NP}. A certificate is an assignment and evaluating CNF is linear in its size.

SAT is NP-hard. Let L∈NPL \in \mathsf{NP} have verifier VV, polynomials pp (certificate) and qq (time), and input xx. Compute φx\varphi_x as above. Show φx\varphi_x satisfiable iff x∈Lx \in L.

(⇐\Leftarrow) If x∈Lx \in L, a certificate ww exists with V(x,w)=1V(x, w) = 1 and computation accepts in ≤T\le T steps. Its tableau (with final configuration repeated through row TT) gives an assignment: xi,j,s=1x_{i,j,s} = 1 iff cell (i,j)(i, j) contains ss. It satisfies φcelda\varphi_{\text{celda}} (one symbol per cell), φinicio\varphi_{\text{inicio}} (row 0 is the initial configuration on ⟨x,w⟩\langle x, w \rangle), φmov\varphi_{\text{mov}} (by locality: each lower cell is FF of the three above) and φacepta\varphi_{\text{acepta}} (last row contains qYq_Y).

(⇒\Rightarrow) Let α\alpha satisfy φx\varphi_x. By φcelda\varphi_{\text{celda}}, α\alpha describes a symbol tableau. By φinicio\varphi_{\text{inicio}}, row 0 is the initial configuration on ⟨x,w⟩\langle x, w \rangle, with ww the bits α\alpha assigns to certificate cells. Induct on ii: if row ii is configuration CiC_i, clauses φmov\varphi_{\text{mov}} say row i+1i + 1 is FF applied cellwise to CiC_i, which by locality is successor Ci+1C_{i+1} (every triple occurring in CiC_i has at most one head, so arbitrary values of FF do not matter). Thus the table is VV’s computation on ⟨x,w⟩\langle x, w \rangle. By φacepta\varphi_{\text{acepta}} row TT contains qYq_Y, so VV accepts ⟨x,w⟩\langle x, w \rangle and x∈Lx \in L.

The reduction is polynomial. φx\varphi_x has O(TW∣S∣3)\bigO(T W \abs{S}^3) clauses, which are O(T2)\bigO(T^2) since ∣S∣\abs{S} is a constant depending on VV not xx; each is written in constant time by consulting FF. Only input-symbol clauses depend on xx. Since TT and WW are polynomials in ∣x∣\abs{x}, computation is polynomial. ■\blacksquare

∎

For the figure’s machine (T=5T = 5; since the head moves only right and halts within four steps, W=7W = 7 columns suffice rather than 2T+m+2=152T + m + 2 = 15 in the general bound; fifteen cell symbols), the formula has 630 variables and 91 085 clauses, or 14 045 if only triples with at most one head are written, the only ones possible. In code you will build it and use a SAT solver from scratch to check its models are exactly the five certificates accepted by the machine.

What it does and does not say

The reduction is universal: it depends not on which problem LL is, only its verifier. And it preserves certificates: a satisfying assignment of φx\varphi_x contains certificate ww in free row-0 cells (and conversely). This later converts decision to search. Quadratic size can be improved: simulating a machine whose head always moves the same way (Pippenger and Fischer, 1979) needs only O(Tlog⁡T)\bigO(T \log T). Alternatively, construct a Boolean circuit simulating the machine and use the Tseitin transformation to obtain an equisatisfiable linear-size CNF: another route to the same result.

What it does not say: SAT is not proven intractable (we do not know whether P=NP\mathsf{P} = \mathsf{NP}), nor is the construction necessarily practical (constants are huge: 91 085 clauses for a five-step machine and three bits). It says that a polynomial SAT algorithm would solve all NP\mathsf{NP} problems in polynomial time; and meanwhile, proving a problem NP-complete proves it is equivalent to SAT.

coNP and the missing symmetry

The definition of NP\mathsf{NP} is asymmetric: yes has a short certificate, no need not. Reversing that asymmetry gives another class.

Examples: tautology (is a formula true under every assignment?), whose no has a short certificate, a falsifying assignment; unsatisfiability (UNSAT), SAT’s complement; and non-Hamiltonian, Hamiltonian cycle’s complement. By definition the complement of an NP\mathsf{NP} problem lies in coNP\mathsf{coNP}. No short certificate is known for nonexistence of a Hamiltonian cycle or unsatisfiability, and conjecturally none exists.

Two facts relate these classes to the above.

  • P⊆NP∩coNP\mathsf{P} \subseteq \mathsf{NP} \cap \mathsf{coNP} because P\mathsf{P} is closed under complement: flip the answer.
  • If P=NP\mathsf{P} = \mathsf{NP}, then NP=coNP\mathsf{NP} = \mathsf{coNP}, for the same reason. Thus conjecture NP≠coNP\mathsf{NP} \neq \mathsf{coNP} is stronger than P≠NP\mathsf{P} \neq \mathsf{NP}.
Proof

Let A∈NPA \in \mathsf{NP}. Since BB is NP-complete, ff exists with x∈A  ⟺  f(x)∈Bx \in A \iff f(x) \in B, i.e. x∈Aˉ  ⟺  f(x)∈Bˉx \in \bar{A} \iff f(x) \in \bar{B}. Since B∈coNPB \in \mathsf{coNP}, Bˉ∈NP\bar{B} \in \mathsf{NP}, and by part (3) of the reductions theorem, Aˉ∈NP\bar{A} \in \mathsf{NP}, i.e. A∈coNPA \in \mathsf{coNP}. Thus NP⊆coNP\mathsf{NP} \subseteq \mathsf{coNP}. Taking complements gives coNP⊆NP\mathsf{coNP} \subseteq \mathsf{NP}. ■\blacksquare

∎

This has two effects: no NP∩coNP\mathsf{NP} \cap \mathsf{coNP} problem can be NP-complete unless NP=coNP\mathsf{NP} = \mathsf{coNP}. And problems there that appear hard but have short certificates of both kinds signal they are probably not NP-complete.

The other promised half: do we lose anything by deciding instead of searching? For natural problems, no. Suppose a black box says whether a formula is satisfiable but gives no assignment. Find one by testing variables one by one.

Proof

First ask whether φ\varphi is satisfiable; stop if not. Maintain invariant “the current formula is satisfiable.” For v=1,…,nv = 1, \dots, n: substitute xv=1x_v = 1 into the current formula (delete clauses containing literal xvx_v and remove ¬xv\lnot x_v from the rest) and ask if the result is satisfiable. If yes, set xv=1x_v = 1. If no, since current formula was satisfiable but not with xv=1x_v = 1, it is with xv=0x_v = 0: set xv=0x_v = 0 without asking. Either way the resulting formula is satisfiable with one fewer variable. After nn steps all variables are fixed and the assignment satisfies φ\varphi. There were 1+n1 + n calls, each on a formula no larger than φ\varphi. ■\blacksquare

∎

The same idea works for clique: if GG has a size-kk clique, traverse vertices and delete vv if the graph without vv still has a clique of size kk. Each remaining vertex is essential, so remaining vertices form exactly a clique of size kk. This is an exercise activity.

For arbitrary NP\mathsf{NP} problems there is no universal way to delete or fix variables, but none is needed: Cook–Levin covers everything. Reduction from LL to SAT preserves certificates, so obtain an x∈Lx \in L certificate by reading free row-0 cells in a satisfying assignment of φx\varphi_x found by self-reducibility. Thus if P=NP\mathsf{P} = \mathsf{NP}, not only deciding but finding solutions to every NP\mathsf{NP} problem would be polynomial. Another reason to believe P≠NP\mathsf{P} \neq \mathsf{NP}: the opposite world would permit finding proofs of every theorem with a short proof.

Between P\mathsf{P} and NP-complete problems

If P≠NP\mathsf{P} \neq \mathsf{NP}, is every NP\mathsf{NP} problem either polynomial or NP-complete? No. Ladner’s theorem (1975): if P≠NP\mathsf{P} \neq \mathsf{NP}, languages in NP\mathsf{NP} exist outside P\mathsf{P} that are not NP-complete (NP-intermediate problems). The proof diagonalizes against all polynomial algorithms and all reductions simultaneously, producing an artificial language. Natural candidates include factoring and graph isomorphism; Babai (2016) gave a quasipolynomial algorithm 2O((log⁡n)c)2^{\bigO((\log n)^c)} for the latter, making NP-completeness less plausible.

Implementation from scratch

Four cells in order, then a final experiment. First write verifiers and measure their steps; second, a SAT solver and assignment search using only a decision oracle; third, the tiny machine’s Cook–Levin formula and a custom solver to check it; fourth, maximum clique by binary search checked against networkx.

[ ]Verifiers and their stepsBrowser
import random

def verifica_sat(cnf, asignacion):
    """cnf: lista de cláusulas (listas de enteros no nulos: v o -v). asignacion[v]: bool. Devuelve (ok, pasos)."""
    pasos = 0
    for clausula in cnf:
        satisfecha = False
        for lit in clausula:
            pasos += 1
            if asignacion[abs(lit)] == (lit > 0):
                satisfecha = True
                break
        if not satisfecha:
            return False, pasos
    return True, pasos

def verifica_clique(aristas, S):
    E = {frozenset(e) for e in aristas}
    S, pasos = list(S), 0
    for i in range(len(S)):
        for j in range(i + 1, len(S)):
            pasos += 1
            if frozenset((S[i], S[j])) not in E:
                return False, pasos
    return True, pasos

def verifica_suma(nums, objetivo, indices):
    indices = set(indices)
    return sum(nums[i] for i in indices) == objetivo, len(indices)

def sat_plantado(n, m, rng):
    """3-CNF con n variables y m cláusulas que satisface una asignación elegida de antemano."""
    sol = {v: rng.random() < 0.5 for v in range(1, n + 1)}
    cnf = []
    while len(cnf) < m:
        vs = rng.sample(range(1, n + 1), 3)
        c = [v if rng.random() < 0.5 else -v for v in vs]
        if any(sol[abs(l)] == (l > 0) for l in c):
            cnf.append(c)
    return cnf, sol

rng = random.Random(1)
print("   n     m   ok   pasos   pasos/(3m)")
for n in (100, 200, 400, 800):
    cnf, sol = sat_plantado(n, 4 * n, rng)
    ok, pasos = verifica_sat(cnf, sol)
    print(f"{n:4d} {4*n:5d}  {ok}  {pasos:6d}   {pasos / (3 * 4 * n):.3f}")

# un clique de tamaño 12 en un grafo aleatorio de 60 vértices, y un certificado falso
aristas = [(i, j) for i in range(60) for j in range(i + 1, 60) if rng.random() < 0.3]
S = list(range(12))
aristas += [(i, j) for i in S for j in S if i < j]
print("clique verdadero:", verifica_clique(aristas, S), "  certificado falso:", verifica_clique(aristas, list(range(5, 17))))
nums = [rng.randrange(10**6, 10**7) for _ in range(30)]
idx = rng.sample(range(30), 8)
print("suma de subconjuntos:", verifica_suma(nums, sum(nums[i] for i in idx), idx))

SAT-verifier steps are about half of 3m3m, always bounded by formula literal count. No exploration occurs: the certificate is read once. Now the solver and oracle.

[ ]From decision oracle to assignmentBrowser
def simplifica(cnf, lit):
    """Pone el literal lit a verdadero. Si aparece una cláusula vacía, el resultado la contiene."""
    nuevo = []
    for c in cnf:
        if lit in c:
            continue
        nuevo.append([l for l in c if l != -lit] if -lit in c else c)
    return nuevo

def dpll(cnf):
    """Decide SAT con propagación unitaria y ramificación (DPLL). cnf: lista de listas de enteros."""
    while True:
        if any(len(c) == 0 for c in cnf):
            return False
        unit = next((c[0] for c in cnf if len(c) == 1), None)
        if unit is None:
            break
        cnf = simplifica(cnf, unit)
    if not cnf:
        return True
    lit = min(cnf, key=len)[0]
    return dpll(simplifica(cnf, lit)) or dpll(simplifica(cnf, -lit))

class Oraculo:
    """Caja negra de decisión que cuenta sus llamadas."""
    def __init__(self, decide):
        self.decide, self.llamadas = decide, 0
    def __call__(self, *args):
        self.llamadas += 1
        return self.decide(*args)

def busca_asignacion(cnf, n, es_sat):
    """Encuentra una asignación usando solo es_sat(cnf) -> bool: n + 1 llamadas si hay solución."""
    if not es_sat(cnf):
        return None
    asignacion = {}
    for v in range(1, n + 1):
        con_v = simplifica(cnf, v)
        if es_sat(con_v):                       # x_v = 1 sigue siendo satisfacible
            cnf, asignacion[v] = con_v, True
        else:                                   # entonces x_v = 0 lo es, sin preguntar
            cnf, asignacion[v] = simplifica(cnf, -v), False
    return asignacion

rng = random.Random(5)
for n in (10, 20, 30):
    cnf, _ = sat_plantado(n, 3 * n, rng)
    orac = Oraculo(dpll)
    a = busca_asignacion(cnf, n, orac)
    print(f"n = {n}: llamadas = {orac.llamadas} (n + 1 = {n + 1}),  la asignación satisface la fórmula: {verifica_sat(cnf, a)[0]}")

orac = Oraculo(dpll)
print("insatisfacible (x1)(¬x1):", busca_asignacion([[1], [-1]], 1, orac), " llamadas:", orac.llamadas)

The returned assignment is the first found by trying 1 before 0 for each variable and need not match the planted one. The important part is the count: exactly n+1n + 1 calls, even if the solver internally explores many more branches.

Now Cook–Levin. The machine is the figure’s. Rows, columns and cell alphabet are defined above; F implements the local rule; and to avoid trusting F, acepta_directo independently simulates the machine.

[ ]The Cook–Levin formula for the tiny machineBrowser
import time
from itertools import combinations, product

TAPE = "01_"
HALT = "YN"
DELTA = {("A", "0"): ("A", "0", "R"), ("A", "1"): ("B", "1", "R"), ("A", "_"): ("Y", "_", "R"),
         ("B", "0"): ("A", "0", "R"), ("B", "1"): ("N", "1", "R"), ("B", "_"): ("Y", "_", "R")}
SIMBOLOS = list(TAPE) + [q + a for q in "ABYN" for a in TAPE]     # 15 símbolos: cinta o cabezal (estado + símbolo)
COLS, FILAS = 7, 6
cabezal = lambda s: len(s) == 2

def F(izq, c, der):
    """Nuevo contenido de una celda a partir de las tres de encima."""
    if cabezal(c):
        return c if c[0] in HALT else DELTA[(c[0], c[1])][1]
    if cabezal(izq) and izq[0] not in HALT and DELTA[(izq[0], izq[1])][2] == "R":
        return DELTA[(izq[0], izq[1])][0] + c
    if cabezal(der) and der[0] not in HALT and DELTA[(der[0], der[1])][2] == "L":
        return DELTA[(der[0], der[1])][0] + c
    return c

def acepta_directo(bits):
    """Simulador de la máquina, independiente de F."""
    cinta, q, pos = ["_"] + [str(b) for b in bits] + ["_"] * 3, "A", 1
    while q not in HALT:
        q, escribe, mov = DELTA[(q, cinta[pos])]
        cinta[pos] = escribe
        pos += 1 if mov == "R" else -1
    return q == "Y"

def var(i, j, s):
    return 1 + (i * COLS + j) * len(SIMBOLOS) + SIMBOLOS.index(s)

NV = FILAS * COLS * len(SIMBOLOS)

def construye_cnf(solo_admisibles):
    cl = []
    for i in range(FILAS):                                   # cada celda tiene exactamente un símbolo
        for j in range(COLS):
            vs = [var(i, j, s) for s in SIMBOLOS]
            cl.append(vs)
            cl += [[-a, -b] for a, b in combinations(vs, 2)]
    cl += [[var(0, 0, "_")], [var(0, 1, "A0"), var(0, 1, "A1")],        # inicio: cabezal en A sobre w1
           [var(0, 2, "0"), var(0, 2, "1")], [var(0, 3, "0"), var(0, 3, "1")]]   # w2 y w3 libres
    cl += [[var(0, j, "_")] for j in (4, 5, 6)]
    cl.append([var(FILAS - 1, j, "Y" + a) for j in range(COLS) for a in TAPE])  # alguna celda con el cabezal en Y
    for i in range(1, FILAS):                                # movimiento: una cláusula por celda y terna de encima
        for j in range(COLS):
            for l, c, r in product(SIMBOLOS if j > 0 else [None], SIMBOLOS, SIMBOLOS if j < COLS - 1 else [None]):
                if solo_admisibles and sum(cabezal(x) for x in (l, c, r) if x) > 1:
                    continue
                lits = [-var(i - 1, j + dj, x) for dj, x in ((-1, l), (0, c), (1, r)) if x]
                cl.append(lits + [var(i, j, F(l or "_", c, r or "_"))])
    return cl

def resuelve(cnf, nv=NV):
    """DPLL con propagación unitaria por listas de ocurrencias. Devuelve val[1..nv] (1 = verdadero) o None."""
    idx = lambda l: 2 * l if l > 0 else -2 * l + 1
    ocurre = [[] for _ in range(2 * nv + 2)]
    for k, c in enumerate(cnf):
        for l in c:
            ocurre[idx(l)].append(k)
    val, traza, pila = [0] * (nv + 1), [], []

    def pon(l):
        v = 1 if l > 0 else -1
        if val[abs(l)] == v:
            return True
        if val[abs(l)] == -v:
            return False
        val[abs(l)] = v
        traza.append(abs(l))
        pila.append(l)
        return True

    def propaga():
        while pila:
            l = pila.pop()
            for k in ocurre[idx(-l)]:                        # cláusulas que han perdido un literal
                libres, ultimo, sat = 0, 0, False
                for m in cnf[k]:
                    vm = val[abs(m)] * (1 if m > 0 else -1)
                    if vm == 1:
                        sat = True
                        break
                    if vm == 0:
                        libres, ultimo = libres + 1, m
                if sat:
                    continue
                if libres == 0 or (libres == 1 and not pon(ultimo)):
                    pila.clear()
                    return False
        return True

    def busca():
        v = next((x for x in range(1, nv + 1) if val[x] == 0), None)
        if v is None:
            return True
        for lit in (v, -v):
            marca = len(traza)
            if pon(lit) and propaga() and busca():
                return True
            pila.clear()
            while len(traza) > marca:
                val[traza.pop()] = 0
        return False

    for c in cnf:
        if len(c) == 1 and not pon(c[0]):
            return None
    return val if propaga() and busca() else None

completa, admisible = construye_cnf(False), construye_cnf(True)
print(f"variables: {NV},  cláusulas: {len(completa)} (todas las ternas) o {len(admisible)} (solo ternas con a lo sumo un cabezal)")

def certificado(val):
    return "".join(next(s for s in "01" if val[var(0, j, s)] == 1 or val[var(0, j, "A" + s)] == 1) for j in (1, 2, 3))

t0, cnf, modelos = time.time(), list(admisible), []
while True:                                                  # todos los modelos, bloqueando el certificado hallado
    val = resuelve(cnf)
    if val is None:
        break
    bits = certificado(val)
    modelos.append(bits)
    cnf.append([-var(0, 1, "A" + bits[0]), -var(0, 2, bits[1]), -var(0, 3, bits[2])])
aceptados = sorted("".join(map(str, b)) for b in product((0, 1), repeat=3) if acepta_directo(b))
print("certificados que dan una fórmula satisfacible:", sorted(modelos))
print("certificados que acepta la máquina (simulador): ", aceptados, "   coinciden:", sorted(modelos) == aceptados)

for bits in ("101", "011"):                                  # fijar el certificado y mirar la tabla
    unidades = [[var(0, 1, "A" + bits[0])], [var(0, 2, bits[1])], [var(0, 3, bits[2])]]
    val = resuelve(admisible + unidades)
    print(f"\ncertificado {bits}:", "fórmula insatisfacible (la máquina rechaza)" if val is None else "tabla leída del modelo")
    if val is not None:
        for i in range(FILAS):
            print("  ", " ".join(f"{next(s for s in SIMBOLOS if val[var(i, j, s)] == 1):>2}" for j in range(COLS)))

Formula models are exactly the accepted certificates: the reduction is correct both ways, as required. Notice the second experiment: with certificate 011 the formula is unsatisfiable, not because the tableau is missing anything but because no legal tableau ends in acceptance. Windows force computation and only the certificate was free.

The fourth cell implements optimization-to-decision reduction for maximum clique with a brute-force oracle as black box, checking against networkx’s maximum clique (Bron–Kerbosch).

[ ]From maximum clique to a decision oracleBrowser
from itertools import combinations
from math import ceil, log2
import networkx as nx

def hay_clique(vertices, aristas, k):
    """Oráculo de decisión (por fuerza bruta): ¿hay k vértices de `vertices` dos a dos adyacentes?"""
    V = sorted(vertices)
    E = {frozenset(e) for e in aristas if e[0] in vertices and e[1] in vertices}
    return any(all(frozenset(p) in E for p in combinations(c, 2)) for c in combinations(V, k))

def omega_por_decision(vertices, aristas, oraculo):
    """Tamaño del clique máximo con búsqueda binaria sobre k: como mucho ceil(log2 n) preguntas."""
    lo, hi = 1, len(vertices)            # todo grafo no vacío tiene un clique de tamaño 1
    while lo < hi:
        mid = (lo + hi + 1) // 2
        if oraculo(vertices, aristas, mid):
            lo = mid
        else:
            hi = mid - 1
    return lo

def omega_networkx(n, aristas):
    """Referencia independiente: clique máximo exacto de networkx (enumera los cliques maximales)."""
    G = nx.Graph()
    G.add_nodes_from(range(n))
    G.add_edges_from(aristas)
    return max(len(c) for c in nx.find_cliques(G))

rng = random.Random(3)
print("  n   p   omega (networkx)  omega (búsqueda binaria)  llamadas  ceil(log2 n)")
for n, p in [(8, 0.5), (12, 0.4), (14, 0.6), (16, 0.5), (16, 0.8)]:
    aristas = [(i, j) for i in range(n) for j in range(i + 1, n) if rng.random() < p]
    orac = Oraculo(hay_clique)
    w = omega_por_decision(set(range(n)), aristas, orac)
    ref = omega_networkx(n, aristas)
    assert w == ref
    print(f"{n:3d} {p:4.1f}  {ref:16d}  {w:24d}  {orac.llamadas:8d}  {ceil(log2(n)):12d}")

Binary search computes only the optimum value. Constructing the clique needs the self-reduction above: another nn calls, O(n)\bigO(n) decision-oracle calls total.

A final experiment reinforces a warning: “NP-complete” describes worst case. Random 3-SAT formulas with mm clauses on nn variables are almost always satisfiable when m/nm/n is small and almost always unsatisfiable when large, with a sharp transition around m/n≈4.27m/n \approx 4.27 (empirical, not proved for 3-SAT). Measure our DPLL’s search-node work versus ratio m/nm/n.

[ ]Where the hard 3-SAT instances areBrowser
nodos = 0

def dpll_cuenta(cnf):
    global nodos
    nodos += 1
    while True:
        if any(len(c) == 0 for c in cnf):
            return False
        unit = next((c[0] for c in cnf if len(c) == 1), None)
        if unit is None:
            break
        cnf = simplifica(cnf, unit)
    if not cnf:
        return True
    lit = min(cnf, key=len)[0]
    return dpll_cuenta(simplifica(cnf, lit)) or dpll_cuenta(simplifica(cnf, -lit))

def al_azar(n, m, rng):
    return [[v * rng.choice((-1, 1)) for v in rng.sample(range(1, n + 1), 3)] for _ in range(m)]

rng, n, N = random.Random(7), 40, 20
print(f"n = {n} variables, {N} fórmulas por razón")
print(" m/n   satisfacibles   nodos medios")
for razon in (2, 3, 4, 4.26, 5, 6, 8, 10):
    total, sat = 0, 0
    for _ in range(N):
        nodos = 0
        sat += dpll_cuenta(al_azar(n, round(razon * n), rng))
        total += nodos
    print(f"{razon:4}   {sat:5d} de {N}      {total / N:8.1f}")

Solver work is small at both extremes (almost everything is satisfiable and a solution is quickly found, or almost everything unsatisfiable with early conflicts) and largest near the transition: with only 40 variables, about four times as many nodes at m/n=4.26m/n = 4.26 as m/n=10m/n = 10, with the gap growing rapidly in nn. This helps explain why modern clause-learning SAT solvers handle huge industrial instances: NP-completeness says hard instance families exist, not that all are hard.

The professional version

In production, use a SAT solver instead of writing one. CDCL solvers (conflict-driven clause learning, covered internally in classical AI) descend from GRASP (1996) and Chaff (2001), routinely solving industrial instances with hundreds of thousands or millions of variables and clauses, as annual SAT competitions show. Common libraries expose an interface much like our oracle:

from pysat.solvers import Glucose3          # pip install python-sat; no se ejecuta en el navegador
import networkx as nx

with Glucose3(bootstrap_with=[[1, 2, -3], [-1, 3], [-2, -3]]) as s:
    print(s.solve())                         # decisión: True
    print(s.get_model())                     # búsqueda: una asignación, como [1, -2, -3]
    print(s.solve(assumptions=[1, 3]))       # el oráculo con variables fijadas, sin recopiar la fórmula

G = nx.gnp_random_graph(30, 0.5, seed=1)
omega = max(len(c) for c in nx.find_cliques(G))     # clique máximo exacto (Bron-Kerbosch), exponencial en el peor caso

Two details: solve(assumptions=...) is exactly self-reducibility’s “fix xv=1x_v = 1 and ask” without rebuilding the formula, and is how model enumeration and SAT optimization are implemented. And constrained integer combinatorial optimization commonly uses CP-SAT or integer programming solvers, internally doing what our binary search does: improve a bound and ask whether a better solution exists.

Common mistakes

Exercises

QuizWhat is known to be in NP?
For which of these problems is there a known proof of membership in NP?

More than one answer may be correct.

NumericQueries to determine the optimum
A salesperson visits 50 cities with integer distances between 1 and 10610^6. You have an oracle answering ‘is there a tour costing at most BB?’. Using binary search over BB, how many queries suffice in the worst case to find the optimal cost?
NumericQueries to find an assignment
A satisfiable CNF has 50 variables. Using the algorithm from the lesson, how many calls to the SAT decision black box are needed to obtain a satisfying assignment?
NumericThe size of a computation tableau
A Turing machine has 4 tape symbols (including blank) and 5 states (including both halting states). For an input with a tableau of 12 rows and 20 columns, using the lesson's encoding, where a cell contains a tape symbol or a head (state and symbol), how many xi,j,sx_{i,j,s} variables does the formula have?
QuizIs it polynomial?
Dynamic programming for subset sum takes O(n t)\bigO(n\,t) steps with nn numbers and target tt. Since subset sum is NP-complete, what can be concluded?
QuizFind the error
Someone writes: ‘To prove my problem XX is easy, I reduce SAT to XX in polynomial time: given a formula, I construct an instance of XX with the same answer. Since SAT solvers are very fast, XX is easy.’ What is the error?
QuizWhat is known and unknown
Which of these statements are currently known to be true (with proof)?

More than one answer may be correct.

ProofReductions: easiness and transitivity
Prove: If A≤pBA \le_p B and B∈PB \in \mathsf{P}, then A∈PA \in \mathsf{P}. If also B≤pCB \le_p C, then A≤pCA \le_p C.
0
Let ff be a reduction from AA to BB computable in time c ∣x∣ac\,\abs{x}^a, and let gg be a reduction from BB to CC computable in time d ∣y∣bd\,\abs{y}^b.

Step 1 of 4. What algorithm decides AA when B∈PB \in \mathsf{P}?

ProofA tableau is a computation if and only if all its windows are legal
Prove: Let VV be a deterministic machine and TT a time bound. A tableau of T+1T + 1 rows whose row 0 is the initial configuration and in which all $2\times 3$ windows are legal (each lower cell equals FF of the three above) is the tableau of the computation of VV. Conversely, the tableau of the computation of VV has all windows legal.
0
By locality, if CC is a configuration and C′C' its successor, Cj′=F(Cj−1,Cj,Cj+1)C'_j = F(C_{j-1}, C_j, C_{j+1}) for every column jj.

Step 1 of 5. How do we prove that each row ii is the configuration CiC_i after ii steps?

CodeA clique with a decision oracle
Implement busca_clique(vertices, aristas, k, oraculo). oraculo(vertices, aristas, k) is a black box that answers whether the graph formed by those vertices (and the edges between them) has a clique of size at least k. Your function returns a list of exactly k vertices forming a clique, or None if none exists, and can call the oracle at most `n + 1` times (n is the number of vertices). Use only the oracle to decide; the tests count calls. Hint: the approach is the self-reducibility you just saw for SAT.
def busca_clique(vertices, aristas, k, oraculo):
  """Devuelve k vertices que formen un clique, o None, usando solo el oraculo de decision."""
  # tu codigo
  return None
Shift+Enter to run

Summary

Key idea
Checking a solution is easy and finding it seems hard; NP-completeness theory turns this intuition into a precise hierarchy: SAT is the hardest NP\mathsf{NP} problem (Cook–Levin, because any polynomial verifier execution fits in CNF), and each polynomial reduction transfers hardness from one problem to another, never backward.
  • A decision problem is language L⊆{0,1}∗L \subseteq \{0,1\}^*; optimization reduces to decision by threshold binary search and search reduces to decision by testing variables one by one with O(n)\bigO(n) calls. Input size is its bit count.
  • P\mathsf{P} is polynomial-time decidability, robust across computation models. NP\mathsf{NP} consists of problems with short polynomially checkable certificates, or equivalently decided by nondeterministic machines in polynomial time. P⊆NP⊆EXP\mathsf{P} \subseteq \mathsf{NP} \subseteq \mathsf{EXP}, and one inclusion is strict but which is unknown.
  • A≤pBA \le_p B means a polynomial function maps AA instances to BB instances with the same answer: BB is at least as hard as AA. Easiness goes against the arrow and hardness along it. To prove CC hard, reduce a hard problem to CC.
  • NP-complete means NP-hard and in NP\mathsf{NP}. An NP-complete problem in P\mathsf{P} implies P=NP\mathsf{P} = \mathsf{NP}. Cook–Levin gives the first: any verifier’s TT-step execution is encoded in a tableau of O(T2)\bigO(T^2) cells, with cell, start, movement (2×32\times 3 windows, one 4-literal clause per upper triple) and acceptance clauses.
  • coNP\mathsf{coNP} is the class of complements of NP\mathsf{NP}. An NP-complete problem in coNP\mathsf{coNP} collapses NP\mathsf{NP} and coNP\mathsf{coNP}. Factoring and linear programming (before 1979) lay in NP∩coNP\mathsf{NP} \cap \mathsf{coNP}, suggesting they were not NP-complete.
  • NP-hard does not mean impractical: SAT solvers handle enormous instances, and difficult random instances cluster in a narrow clause-to-variable-ratio region.