Module contents
Lesson 28 of 33Core 120 min

The art of reductions: a catalogue of NP-complete problems

Proving NP-completeness is a design skill: choose a source problem and build gadgets. Follow Karp's reduction tree from 3-SAT to independent set, clique and vertex cover, 3-coloring, Hamiltonian cycle and traveling salesperson, subset sum and partition. Distinguish weak from strong NP-hardness and extract reduction design patterns for new problems.

After this lesson you can

  • Construct and prove reductions from 3-SAT to independent set, 3-coloring, Hamiltonian cycle and subset sum.
  • Design choice and checking gadgets for new reductions.
  • Distinguish strong and weak NP-hardness and relate them to pseudopolynomial algorithms.
  • Choose the most suitable source problem to prove a new problem NP-complete.
  • Automatically check reductions with a solver on small instances.

Before you start

Motivation: is an exact algorithm worth seeking?

Your platform team has nn integration test suites and a CI cluster. Two suites conflict if they need the same test database or port: they cannot run together. Two nearly identical questions arise. What is the largest number of suites that can run simultaneously? How many rounds are needed to distribute them so that no two suites in a round conflict? A colleague has spent a week trying to write an efficient exact algorithm. Before spending another week it is useful to know whether one exists.

The questions are, respectively, maximum independent set and minimum coloring on the conflict graph. The previous lesson established the theoretical tool: the Cook–Levin theorem gives a first NP-complete problem, SAT, and a polynomial reduction propagates hardness to any problem SAT reduces to. This lesson is about how to do that in practice. Proving a new problem NP-complete is a design skill, much like writing a small compiler: choose a suitable source problem, design local pieces (gadgets) that translate its elements into the target language, and prove that the translation preserves the answer in both directions.

The result saves money. If you prove your problem NP-complete, you stop looking for a polynomial exact algorithm (which would prove P=NP\mathrm{P} = \mathrm{NP}) and turn to the realistic tools in lessons 30 and 31: branch and bound, parameterized algorithms, approximation and SAT solvers. The catalogue we build here (independent set, clique, cover, coloring, Hamiltonian cycle, traveling salesperson, subset sum, partition) is also the repertoire of source problems you will choose from.

The recipe for an NP-completeness proof

Recall the scheme. A problem QQ is NP-complete if it belongs to NP and every problem in NP reduces to it in polynomial time. Since reduction is transitive, for a new problem it suffices to reduce one known problem.

The proof composes reductions: if L≤pPL \le_p P via gg, then L≤pQL \le_p Q via f∘gf \circ g, and the composition of two polynomial functions is polynomial. For design, what matters is how the work divides up. Every proof has five obligations, and beginners’ errors almost always occur in the third and fifth.

  1. Membership in NP. There is a polynomial-size certificate and a polynomial verifier (almost always trivial, but it must be stated).
  2. Choice of source. A known NP-complete problem PP with structure similar to QQ.
  3. Construction. A function ff from instances of PP to instances of QQ, computable in polynomial time. This includes f(x)f(x) having polynomial size in ∣x∣\abs{x} under the agreed input encoding.
  4. Forward direction. If xx is positive, f(x)f(x) is positive: construct a target solution from a source solution.
  5. Reverse direction. If f(x)f(x) is positive, xx is positive: recover a source solution from a target solution.

All reductions in this lesson also translate certificates in both directions using functions you will implement in the lab: from an assignment to an independent set and back. This is the level of rigor worth demanding, and it also allows automatic checking.

From SAT to 3-SAT

The reduction from SAT to 3-SAT is the first step. SAT permits clauses of any length; 3-SAT requires at most three literals per clause (or exactly three, depending on the version). A single problem with uniform structure is much more convenient as a source: the gadgets in the following sections are designed for fixed-size clauses.

The idea is to split each long clause with new variables linking its pieces. For a clause (l1∨l2∨⋯∨lk)(l_1 \lor l_2 \lor \cdots \lor l_k) with k≥4k \ge 4, introduce y1,…,yk−3y_1, \dots, y_{k-3} and replace it by

(l1∨l2∨y1)∧(¬y1∨l3∨y2)∧⋯∧(¬yk−4∨lk−2∨yk−3)∧(¬yk−3∨lk−1∨lk).(l_1 \lor l_2 \lor y_1) \land (\neg y_1 \lor l_3 \lor y_2) \land \cdots \land (\neg y_{k-4} \lor l_{k-2} \lor y_{k-3}) \land (\neg y_{k-3} \lor l_{k-1} \lor l_k).

Each yiy_i says “the true literal appears later.” Short clauses are padded: (l)(l) becomes the four clauses (l∨y∨z)(l∨¬y∨z)(l∨y∨¬z)(l∨¬y∨¬z)(l \lor y \lor z)(l \lor \neg y \lor z)(l \lor y \lor \neg z)(l \lor \neg y \lor \neg z) with new y,zy, z, and (l1∨l2)(l_1 \lor l_2) becomes (l1∨l2∨y)(l1∨l2∨¬y)(l_1 \lor l_2 \lor y)(l_1 \lor l_2 \lor \neg y).

Proof

The size is linear: a clause of k≥3k \ge 3 literals produces k−2k - 2 clauses and one of 1 or 2 literals produces 4 or 2. It suffices to prove each clause C=(l1∨⋯∨lk)C = (l_1 \lor \cdots \lor l_k) with k≥4k \ge 4 satisfies the equivalence separately, using distinct new variables in each clause; the short clauses are immediate.

Forward. Given an assignment making some ltl_t true, set yi=1y_i = 1 for i≤t−2i \le t - 2 and yi=0y_i = 0 for i≥t−1i \ge t - 1. Clause ii (2≤i≤k−32 \le i \le k - 3), (¬yi−1∨li+1∨yi)(\neg y_{i-1} \lor l_{i+1} \lor y_i), is true by yiy_i if i≤t−2i \le t - 2, by ltl_t if i=t−1i = t - 1 and by ¬yi−1\neg y_{i-1} if i≥ti \ge t. The edge cases (first and last clause, t∈{1,2}t \in \{1, 2\} or t≥k−1t \ge k - 1) are equally straightforward.

Reverse. If all lil_i were false, the first clause forces y1=1y_1 = 1, the second y2=1y_2 = 1, and so on until yk−3=1y_{k-3} = 1, and the last clause (¬yk−3∨lk−1∨lk)(\neg y_{k-3} \lor l_{k-1} \lor l_k) is false. Thus an assignment satisfying φ′\varphi' makes an original literal of CC true, and restricted to variables of φ\varphi satisfies CC.

∎

Notice what is preserved: satisfiability, not models. φ\varphi and φ′\varphi' are not logically equivalent (they have different variables and different numbers of solutions): they are equisatisfiable. Polynomial reductions ask for exactly that.

Why 2-SAT is easy and where the trick breaks

Why stop at three? With two literals per clause, the problem stops being hard. A clause (a∨b)(a \lor b) is equivalent to the two implications ¬a→b\neg a \to b and ¬b→a\neg b \to a. The implication graph has a vertex per literal and these arcs, and the 2-CNF formula is unsatisfiable if and only if some variable xx and its negation ¬x\neg x are in the same strongly connected component (from xx one reaches ¬x\neg x and vice versa: contradiction). With lesson 18 this is a linear algorithm.

The clause-splitting trick cannot go below three: (a∨b∨c)(a \lor b \lor c) cannot be written as a conjunction of two-literal clauses, even with auxiliary variables. The reason is elegant: if three assignments satisfy a 2-CNF, their coordinate-wise majority also satisfies it (in each clause (u∨v)(u \lor v), each of the three makes uu or vv true, so one is true in at least two), and that property survives ignoring auxiliary variables. But (1,0,0)(1,0,0), (0,1,0)(0,1,0) and (0,0,1)(0,0,1) satisfy (a∨b∨c)(a \lor b \lor c) while their majority, (0,0,0)(0,0,0), does not. There is a deeper reason, resolution: from two 2-literal clauses (x∨a)(x \lor a) and (¬x∨b)(\neg x \lor b) one derives (a∨b)(a \lor b), again with 2 literals; the resolution closure has at most (2n)2(2n)^2 clauses and can be computed in polynomial time. With 3-literal clauses, (x∨a∨b)(x \lor a \lor b) and (¬x∨c∨d)(\neg x \lor c \lor d) produce (a∨b∨c∨d)(a \lor b \lor c \lor d) of size 4, and the closure can grow exponentially. The boundary between P and NP-complete is exactly between 2 and 3.

Independent set, clique and vertex cover

From 3-SAT to the first graph problem. A set of vertices is independent if no two of them are joined by an edge. The independent set problem asks, given a graph GG and integer kk, whether an independent set of size at least kk exists. Its two siblings are clique (a set of pairwise adjacent vertices) and vertex cover (a set touching every edge); the family is completed by complementation, as we will see.

The construction has two gadgets, one for each thing the formula must enforce. Given a 3-CNF formula φ\varphi with mm clauses, graph GφG_\varphi has:

  • Choice gadget. For each clause CjC_j, a triangle with three vertices, one per literal. Since they are adjacent, an independent set takes at most one per triangle: the literal that “serves” the clause.
  • Consistency gadget. An edge between each literal xx and each literal ¬x\neg x from different clauses. Thus xx and ¬x\neg x are never selected together.

The target is k=mk = m: one vertex per clause.

InteractiveFrom 3-SAT to independent set
C₁✓C₂✓C₃✓C₄✗x₁¬x₂x₃¬x₁x₂x₃x₁x₂¬x₃¬x₁¬x₂¬x₃Target: independent set of size k = 4
  • triangle edge (one choice per clause)
  • conflict edge (opposite literals)
  • chosen vertex
Target k = m
Clause C4C_4 has no true literal: no vertex can be chosen in its triangle, so the set has 3 of 44. This assignment does not work; is there another?
Variables
C₁
C₂
C₃
C₄
What you choose
Formula(x1∨¬x2∨x3)∧(¬x1∨x2∨x3)∧(x1∨x2∨¬x3)∧(¬x1∨¬x2∨¬x3)(x_{1} \lor \neg x_{2} \lor x_{3}) \land (\neg x_{1} \lor x_{2} \lor x_{3}) \land (x_{1} \lor x_{2} \lor \neg x_{3}) \land (\neg x_{1} \lor \neg x_{2} \lor \neg x_{3})
Vertices3m = 12
Edges12 + 12 = 24
Targetk = m = 4
Satisfying assignments4 of 8
Maximum independent set α(G)4
Induced set3 vertices, independent
Assignment readx₁ = 1 x₂ = 1 x₃ = *
Edit the formula (click a literal to change it) and replay the construction: vertices, triangles, conflict edges and target k=mk = m. Then check both directions of the proof. Under ‘Asignación’ (assignment), click a literal to make it true: each clause chooses its first true literal and the resulting set is independent if and only if the assignment satisfies the formula. Under ‘Conjunto’ (set), select vertices manually: conflicting edges turn red and, if you reach mm conflict-free vertices, the assignment is read. Try the unsatisfiable formula: what is the largest independent set? What does α(G)\alpha(G) count in general?
Proof

Forward. Let aa be an assignment satisfying φ\varphi. In each clause CjC_j choose a true literal and take its vertex. There are mm vertices, one per triangle, so there are no triangle edges between them. A conflict edge would join a chosen literal xx to a chosen ¬x\neg x, and both would be true under aa, which is impossible.

Reverse. Let SS be an independent set with ∣S∣=m\abs{S} = m. Each triangle contains at most one vertex of SS and there are mm triangles, so there is exactly one per clause. Define the assignment by making every chosen literal true (it is consistent: if xx and ¬x\neg x were both in SS, there would be an edge between them) and assigning any value to variables with no vertex in SS. Every clause has a true literal, so φ\varphi is satisfied.

∎

The size of GφG_\varphi is polynomial: 3m3m vertices and at most 3m+(3m2)3m + \binom{3m}{2} edges. And IS∈NP\mathrm{IS} \in \mathrm{NP} because a set of vertices is its own certificate. Thus independent set is NP-complete.

Clique and vertex cover by complementation

Two almost free reductions complete the family.

Proof

(1)  ⟺  \iff(2): SS has no edges of GG if and only if all pairs in SS are edges of Gˉ\bar G. (1)  ⟺  \iff(3): SS is not independent if and only if there is an edge {u,v}\{u, v\} with u,v∈Su, v \in S, that is, an edge with neither endpoint in V∖SV \setminus S; so SS is independent if and only if every edge has an endpoint in V∖SV \setminus S.

∎

Thus (G,k)↦(Gˉ,k)(G, k) \mapsto (\bar G, k) reduces independent set to clique, and (G,k)↦(G,n−k)(G, k) \mapsto (G, n - k) reduces it to vertex cover. Both are in NP and are NP-complete; the second, with its complete proof, is an exercise. The only cost of the first is constructing the complement, which can have Θ(n2)\Theta(n^2) edges: still polynomial.

3-coloring: palette, variables and the OR gate

Coloring is the prototype problem where the reduction constructs logic with colors. 3-coloring asks whether a graph can be colored with three colors so that no adjacent vertices share a color. The NP-completeness of 3-coloring is proved from 3-SAT using three gadgets.

Palette. A triangle with vertices TT, FF and BB (true, false and “base”). Since they are adjacent, every 3-coloring gives them three distinct colors; without loss of generality call these T\mathsf{T}, F\mathsf{F} and B\mathsf{B}.

Variable. For each xix_i, two vertices xix_i and ¬xi\neg x_i joined to each other and both joined to BB. Neither can have color B\mathsf{B} and they cannot match: one is T\mathsf{T} and the other F\mathsf{F}. Choosing which is T\mathsf{T} is choosing the value of the variable.

OR gate. With inputs a,ba, b and output oo: three new vertices x,y,ox, y, o with edges {a,x}\{a, x\}, {b,y}\{b, y\}, {x,y}\{x, y\}, {x,o}\{x, o\} and {y,o}\{y, o\}. Triangle x,y,ox, y, o uses all three colors.

Proof

(1) Since x≠a=Fx \ne a = \mathsf{F} and y≠b=Fy \ne b = \mathsf{F}, both are T\mathsf{T} or B\mathsf{B}, and since they are adjacent they differ: {x,y}={T,B}\{x, y\} = \{\mathsf{T}, \mathsf{B}\}. The triangle forces o=Fo = \mathsf{F}.

(2) If a=Ta = \mathsf{T}: set x=Fx = \mathsf{F} (allowed because x≠ax \ne a), y=By = \mathsf{B} (allowed because y≠by \ne b, with b∈{T,F}b \in \{\mathsf{T}, \mathsf{F}\}) and o=To = \mathsf{T}. If a=Fa = \mathsf{F} and b=Tb = \mathsf{T}: y=Fy = \mathsf{F}, x=Bx = \mathsf{B} and o=To = \mathsf{T}.

∎

Clause. For Cj=(l1∨l2∨l3)C_j = (l_1 \lor l_2 \lor l_3) chain two gates: o1=OR(l1,l2)o_1 = \mathrm{OR}(l_1, l_2), also joined to BB (so it is T\mathsf{T} or F\mathsf{F}), and o2=OR(o1,l3)o_2 = \mathrm{OR}(o_1, l_3), with o2o_2 joined to FF and BB, forcing it to be T\mathsf{T}. There are six vertices and thirteen edges per clause.

InteractiveThe clause gadget
TFBaFfalsebFfalsecTtruex₁By₁To₁Fx₂By₂Fo₂TpaletteOR gate 1OR gate 2
  • T (true)
  • F (false)
  • B (base)
  • o₂ connected to F and B (forces T)
  • violated edge
Proper gadget colorings by inputs (a,b,c)(a, b, c); select a row to load it
With inputs F, F, T, output o2o_2 can be T: there are 2 proper colorings of the rest of the gadget. At least one input is true.
Input a
Input b
Input c
Clause(a ∨ b ∨ c)
Valuetrue
Proper colorings2
Edges violated in the best attempt0
Gadget vertices and edges6 and 13 (plus 3 connecting to B)
Set the colors of the three inputs and see how the rest is colored (the widget searches all 363^6 cases by brute force). Each input has its letter T, F or B in the corner of its node. With all three inputs false there is no coloring: the best attempt violates one edge, shown in red. The table shows the number of proper colorings for each combination. Disconnect the output from F and B and observe what colors o2o_2 can take: the gate alone permits T but does not force it; those two edges turn ‘can be T’ into ‘must be T’.
Proof

If all are F\mathsf{F}: by (1), o1=Fo_1 = \mathsf{F}; then the second gate has both inputs F\mathsf{F} and by (1) o2=Fo_2 = \mathsf{F}, but o2o_2 is joined to FF. Impossible.

If one is T\mathsf{T}: if l1l_1 or l2l_2 is, by (2) choose o1=To_1 = \mathsf{T}; if l1=l2=Fl_1 = l_2 = \mathsf{F}, by (1) o1=Fo_1 = \mathsf{F} and l3=Tl_3 = \mathsf{T}. In both cases o1∈{T,F}o_1 \in \{\mathsf{T}, \mathsf{F}\} (compatible with its edge to BB) and one input of the second gate is T\mathsf{T}, so by (2) we can choose o2=To_2 = \mathsf{T}, compatible with its edges to FF and BB.

∎
Proof

Forward. Given an assignment satisfying φ\varphi, color the palette T,F,B\mathsf{T}, \mathsf{F}, \mathsf{B}, each true literal T\mathsf{T} and each false literal F\mathsf{F} (consistent with the variable), and complete each clause using the previous theorem, applicable because each clause has a true literal.

Reverse. In a proper 3-coloring, rename the colors so the palette is T,F,B\mathsf{T}, \mathsf{F}, \mathsf{B}. Each literal is joined to BB, so is T\mathsf{T} or F\mathsf{F}, and xix_i, ¬xi\neg x_i have opposite colors: they define the assignment “xix_i is true if and only if its vertex is T\mathsf{T}”. Since each clause gadget is colored, the previous theorem guarantees some input is T\mathsf{T}, i.e. a true literal.

∎

The sizes are checked in the lab: for n=5n = 5 variables and m=8m = 8 clauses the graph has 3+10+48=613 + 10 + 48 = 61 vertices and 122122 edges. And since 3-coloring is in NP (the coloring is the certificate), it is NP-complete. The arbitrary chromatic number and other colorings are NP-hard a fortiori (restriction pattern, below). For the opening example: scheduling suites in three conflict-free rounds is already NP-complete.

Hamiltonian cycles and the traveling salesperson

A Hamiltonian cycle visits each vertex exactly once. The Hamiltonian cycle and its traveling salesperson variant need a more sophisticated gadget: one cannot color or choose vertices, but must force a traversal. We first work with directed graphs.

The construction from 3-SAT to directed Hamiltonian cycle, for φ\varphi with nn variables and mm clauses C1,…,CmC_1, \dots, C_m:

  • Variable ladder. For each xix_i, a row of L=3m+3L = 3m + 3 vertices vi,0,…,vi,L−1v_{i,0}, \dots, v_{i,L-1} with arcs in both directions between consecutive vertices. Traversing it left to right means xi=1x_i = 1; right to left, xi=0x_i = 0.
  • Links. Arcs from a vertex ss to both ends of row 1; from each end of row ii to each end of row i+1i + 1 (four arcs); from both ends of row nn to a vertex tt; and an arc t→st \to s.
  • Clause vertices. A vertex cjc_j per clause. If xi∈Cjx_i \in C_j, arcs vi,3j−1→cj→vi,3jv_{i,3j-1} \to c_j \to v_{i,3j}; if ¬xi∈Cj\neg x_i \in C_j, arcs vi,3j→cj→vi,3j−1v_{i,3j} \to c_j \to v_{i,3j-1}. (As usual, assume no clause contains both xix_i and ¬xi\neg x_i: it would be trivially true and can be removed.) Vertices vi,3j+1v_{i,3j+1}, with 0≤j≤m0 \le j \le m, are separators: one before the first pair, one between every two consecutive pairs and one after the last, none at a row endpoint.

The asymmetry is the key: the detour through cjc_j from left to right exists only for positive literals, and in the opposite direction only for negative ones. A row traversed to the right can visit clauses where xix_i appears positively, precisely those made true by xi=1x_i = 1.

InteractiveThe Hamiltonian cycle ladder
x₁ = T →x₂ = T →x₃ = F ←stC₁via x₁C₂via x₂C₃via ¬x₃
  • induced cycle (thick line, colored by row)
  • unused arcs (thin line)
  • unvisited clause
Complete Hamiltonian cycle: it visits all 41 vertices exactly once. Each row is traversed in the direction of its variable and clauses are visited by detours (C1C_1 via x₁, C2C_2 via x₂, C3C_3 via ¬x₃).
Formula(x1∨¬x2∨x3)∧(¬x1∨x2)∧(¬x2∨¬x3)(x_{1} \lor \neg x_{2} \lor x_{3}) \land (\neg x_{1} \lor x_{2}) \land (\neg x_{2} \lor \neg x_{3})
Verticesn(3m + 3) + m + 2 = 41
Arcs93
Cycle with this assignmentyes
Satisfying assignments3 of 8
Total Hamiltonian cycles5
Each row is a variable. Click its name or use the switches to choose its traversal direction, and watch the cycle (thick line): it starts at ss, goes through the rows one by one and returns from tt to ss, detouring to each clause from a row whose direction makes one of its literals true. If a clause has no true literal, its vertex remains unvisited (red) and there is no cycle. The button sets an assignment satisfying the formula. The last figure counts all Hamiltonian cycles: for each assignment, the product of true literals per clause, because each clause can be visited from any of its true literals. Try the unsatisfiable formula.
Proof

Forward. With an assignment aa satisfying φ\varphi: the cycle starts at ss, traverses row ii left to right if a(xi)=1a(x_i) = 1 and right to left otherwise, passes to the next row at an endpoint and ends at tt with arc t→st \to s. For each clause choose a true literal ll of variable xix_i; when row ii passes positions 3j−1,3j3j-1, 3j, detour through cjc_j: it exists because the row direction makes ll true. Every vertex is visited once.

Reverse. Let HH be a Hamiltonian cycle. Step 1: the detour returns to its row. Suppose HH enters cjc_j from vi,3j−1v_{i,3j-1} (positive literal) and exits to a vertex w≠vi,3jw \ne v_{i,3j}. Then vi,3jv_{i,3j} cannot have predecessor vi,3j−1v_{i,3j-1} (that vertex goes to cjc_j) or cjc_j, so its predecessor is vi,3j+1v_{i,3j+1} and its successor, which cannot be vi,3j+1v_{i,3j+1} (that would form a two-vertex cycle), is vi,3j−1v_{i,3j-1}. But then vi,3j−2v_{i,3j-2}, the previous separator, whose only neighbors are vi,3j−3v_{i,3j-3} and vi,3j−1v_{i,3j-1}, has only vi,3j−3v_{i,3j-3} as possible predecessor (because vi,3j−1v_{i,3j-1} already has a successor) and only vi,3j−3v_{i,3j-3} as possible successor (because vi,3j−1v_{i,3j-1} already has a predecessor): HH would contain the two-vertex cycle vi,3j−3↔vi,3j−2v_{i,3j-3} \leftrightarrow v_{i,3j-2}. Contradiction. The negative case is symmetric, with the next separator vi,3j+1v_{i,3j+1} playing the role of vi,3j−2v_{i,3j-2}; it also works for j=mj = m because vi,3m+1v_{i,3m+1} is not the row endpoint (vi,3m+2v_{i,3m+2} is), which is why every row has a separator beyond its last pair.

Step 2: each row is traversed in one direction. Replacing each detour with the direct arc between its two row vertices, each interior row vertex has only its two row neighbors. If the predecessor of vi,kv_{i,k} is vi,k−1v_{i,k-1}, its successor is vi,k+1v_{i,k+1} and so on to the end, and conversely. Thus the entire row is traversed from one end to the other and rows are visited in order.

Step 3. Define a(xi)=1a(x_i) = 1 if row ii is traversed left to right. Each cjc_j is visited from some row ii by a detour existing only when the row direction makes the literal of xix_i in CjC_j true. Hence aa satisfies every clause.

∎

From directed to undirected. Replace each vertex vv by three, vin,vmid,voutv_{\text{in}}, v_{\text{mid}}, v_{\text{out}}, joined in that order by two edges, and each arc u→vu \to v by edge {uout,vin}\{u_{\text{out}}, v_{\text{in}}\}. A directed cycle gives a cycle traversing each triplet from in\text{in} to out\text{out}. Conversely, vmidv_{\text{mid}} has only two neighbors, so every Hamiltonian cycle goes through vin-vmid-voutv_{\text{in}} \text{-} v_{\text{mid}} \text{-} v_{\text{out}}, and on leaving voutv_{\text{out}} can only enter an uinu_{\text{in}}: all triplets are traversed in the same direction and this is a directed cycle. This is a local replacement: each vertex is replaced by a fixed piece. Undirected Hamiltonian cycle is NP-complete.

Traveling salesperson. The decision problem receives distances d(u,v)d(u, v) between nn cities and a bound DD, and asks whether a tour visits them all with total length at most DD. Given a graph GG with nn vertices, define d(u,v)=1d(u, v) = 1 if {u,v}∈E\{u, v\} \in E and d(u,v)=2d(u, v) = 2 otherwise, with D=nD = n. A Hamiltonian cycle is a tour of length exactly nn; a tour of length nn has nn segments of length 1, so uses only graph edges. One line of proof suffices because traveling salesperson contains Hamiltonian cycle as a special case. Note: the distances are 1 and 2, small numbers, a fact that matters in the strong hardness section.

Subset sum and partition

So far all numbers were small. The subset sum problem receives integers a1,…,ana_1, \dots, a_n and a target TT and asks whether some subset sums to exactly TT; partition asks whether the integers can be split into two groups with equal sum. The reduction from 3-SAT is a beautiful encoding: digits act as independent columns, and the trick is to ensure there are no carries.

Given φ\varphi with nn variables and mm clauses (with distinct variables within each clause), all numbers have n+mn + m decimal digits: the first nn for variables and the last mm for clauses.

  • For each variable xix_i, two numbers viv_i (true) and vi′v_i' (false). Both have a 1 in the digit for xix_i; viv_i also has a 1 in the digit of each clause containing xix_i, and vi′v_i' in that of each clause containing ¬xi\neg x_i. The rest are zeros.
  • For each clause CjC_j, two equal slack numbers, with a single 1 in its digit.
  • The target TT has a 1 in each of the first nn digits and a 3 in each of the last mm.

For example, with φ=(x1∨¬x2∨x3)(¬x1∨x2∨x3)(x1∨x2∨¬x3)(¬x1∨¬x2∨¬x3)\varphi = (x_1 \lor \neg x_2 \lor x_3)(\neg x_1 \lor x_2 \lor x_3)(x_1 \lor x_2 \lor \neg x_3)(\neg x_1 \lor \neg x_2 \lor \neg x_3) (the first interactive formula) there are 2⋅3+2⋅4=142 \cdot 3 + 2 \cdot 4 = 14 7-digit numbers. Separating variable and clause columns, v1=100 ∣ 1010v_1 = 100\,|\,1010 (variable x1x_1 and clauses C1C_1 and C3C_3, where it appears positively), v1′=100 ∣ 0101v_1' = 100\,|\,0101 (with ¬x1\neg x_1 in C2C_2 and C4C_4), the two slack numbers for C1C_1 are 000 ∣ 1000000\,|\,1000, and the target is 111 ∣ 3333111\,|\,3333.

Proof

No carries. Each column sums to at most 5: a variable column receives at most its two numbers, and a clause column at most three literal numbers (one per clause literal) plus the two slack numbers. Since 5<105 < 10, adding integers is equivalent to column-by-column addition, and the target is reached if and only if every column reaches its required sum.

Forward. With an assignment satisfying φ\varphi, take viv_i if xix_i is true and vi′v_i' otherwise: each variable column sums to 1. The column of CjC_j receives as many ones as the clause has true literals, a number tj∈{1,2,3}t_j \in \{1, 2, 3\}; add 3−tj∈{0,1,2}3 - t_j \in \{0, 1, 2\} slack numbers and it sums to 3.

Reverse. If a subset sums to TT, the column of xix_i forces choosing exactly one of vi,vi′v_i, v_i': this defines an assignment. The column of CjC_j sums to 3 with at most 2 from slack, so at least one literal number contributes a 1: a true literal.

∎

The conceptual key is size: the numbers have n+mn + m digits, so their value reaches 10n+m10^{n+m}, exponential in the formula size. The produced instance has Θ((n+m)2)\Theta((n + m)^2) digits in total, so the value of TT is 2Θ(ℓ)2^{\Theta(\sqrt{\ell})} as a function of that length ℓ\ell: superpolynomial, which is what matters. As we will see, this is why the reduction proves only weak NP-hardness.

From subset sum to partition. Given (a1,…,an;T)(a_1, \dots, a_n; T) with S=∑iaiS = \sum_i a_i and 0≤T≤S0 \le T \le S, add the two numbers x=S+Tx = S + T and y=2S−Ty = 2S - T. The total sum is 4S4S, and we seek two groups of sum 2S2S. Since x+y=3S>2Sx + y = 3S > 2S, xx and yy cannot be in the same group (if S>0S > 0); in the group containing yy the rest sums to 2S−y=T2S - y = T. Thus a partition exists if and only if some subset of aia_i sums to TT. If T<0T < 0 or T>ST > S, the answer is no and the instance maps to a fixed negative instance. You will program this reduction.

Knapsack. Knapsack (is there a subset of weight at most WW and value at least VV?) contains subset sum with value equal to weight and W=V=TW = V = T: another restriction. Knapsack is weakly NP-complete and pseudopolynomial dynamic programming solves it in O(nW)\bigO(nW).

Weak and strong NP-hardness

The subset sum reduction creates numbers with n+mn + m digits. Subset sum dynamic programming costs O(nT)\bigO(nT). Does this contradict NP-completeness? No: TT is exponential in n+mn + m, and O(nT)\bigO(nT) is superpolynomial in input length. It is a pseudopolynomial algorithm: polynomial in values, not in the number of bits. Two types of hardness must be distinguished.

Proof

Let pp be the polynomial in the definition. On instances with Max⁡(I)≤p(∣I∣)\operatorname{Max}(I) \le p(\abs{I}), the algorithm time, polynomial in ∣I∣\abs{I} and Max⁡(I)\operatorname{Max}(I), is polynomial in ∣I∣\abs{I}. That restriction is NP-hard and is in P: P=NP\mathrm{P} = \mathrm{NP}.

∎

Consequence: subset sum, partition and knapsack are not strongly NP-hard unless P=NP\mathrm{P} = \mathrm{NP}, since they have pseudopolynomial dynamic programming. Strongly NP-hard problems resist even with small numbers. Three examples:

  • Traveling salesperson already is: the reduction from Hamiltonian cycle uses distances 1 and 2.
  • 3-partition: given 3m3m integers aia_i with B/4<ai<B/2B/4 < a_i < B/2 and sum mBmB, can they be divided into mm triples each summing to BB? Garey and Johnson proved it strongly NP-complete (the reduction, via three-dimensional matching, keeps numbers polynomially bounded; we cite it without proof).
  • Bin packing: do 3m3m items of sizes aia_i fit in mm bins of capacity BB? From 3-partition: bins must be full (the total sum is mBmB) and since B/4<ai<B/2B/4 < a_i < B/2, each bin has exactly three items. So a 3-partition is a packing and vice versa. With polynomial numbers: strong. Scheduling on mm identical machines (minimizing completion time) is proved similarly.

The boundary has a practical interpretation. If your problem only has moderate numbers (times in seconds, weights up to 10610^6) and is weakly hard, DP may solve it in practice; if strongly hard, no scaling trick saves it.

Karp’s map

Karp (1972) brought together 21 problems in a reduction tree rooted at SAT. Each edge is a reduction like those in this lesson. The interactive below contains those 21 and four more we used (independent set, 3-coloring, traveling salesperson and 3-partition), with the paths followed here (which sometimes differ from Karp’s: each edge says so). Click a problem to see its reduction gadget, solution translation, instance size and a worked example; try adding your own problem.

InteractiveKarp’s reduction tree
SAT0–1 integer LP3-SATIndependent setCliqueSet packingVertex coverSet coverSteiner treeFeedback verticesFeedback arcs3-coloringChromatic numberClique coverExact coverHitting set3D matching3-partitionDirected Ham. cycleHamiltonian cycleTraveling salesmanSubset sumJob sequencingPartitionMax cut
3-SAT ≤p\le_p Independent set

The problem

Given a graph and kk, are there kk vertices with no edges between them?

Reduction idea

One triangle per clause (one choice per clause) and one edge between each literal and its negation (consistency). We ask for an independent set of size k=mk = m.

From solution to solution

Satisfying assignment →\to one true literal per clause. Independent set of size mm →\to chosen literals are true; remaining variables are free.

Instance size

3m3m vertices and 3m3m triangle edges plus one for each pair of opposite literals from different clauses.

Calculated example

Example formula (n=3n = 3, m=4m = 4): 12 vertices, 24 edges (12 triangle and 12 conflict) and k=4k = 4.

Where

Section “Independent set”. Interactive 1.
  • Karp problem (1972)
  • added in the lesson (square)
  • reduction developed in the lesson (filled)
  • chain to selected problem
  • your unproven problem
Still needed: NP membership; polynomial-time computation; “source ⇒ target” direction; “target ⇒ source” direction. Without this, the reduction remains a proposal and the node is drawn with a dashed outline.
SelectedIndependent set
Steps from SAT2
ChainSAT → 3-SAT → Independent set
StatusNP-complete
Problems in the tree25 + 0 of yours
Each problem hangs from the one it is reduced from. Click one to see its edge gadget, how solutions translate, instance size and a worked example. The thick blue line is the chain of reductions from SAT; its length is what gets composed. Below, propose your own problem: choose a source and mark what you have proved. Try choosing a source in P (the proof, even if correct, proves nothing), marking only one direction of the equivalence, and hanging a problem from another of yours that is not yet proved.

Two observations about the map. First is economy: a short chain from SAT reaches almost everything, and each new edge only requires designing one gadget. Second is size: composing rr reductions whose size grows like ncn^{c} gives a final instance of size ncrn^{c^r}, polynomial as long as rr is constant. This does not matter in a fixed-depth tree, but it is useful to choose sources close to the target (shorter, less blowup, simpler gadgets).

Reduction design patterns

Looking at the previous reductions reveals a repertoire. We call these reduction design patterns.

Restriction. The target contains the source as a special case, and the reduction is (almost) the identity. 3-coloring ≤p\le_p chromatic number (k=3k = 3); subset sum ≤p\le_p knapsack (value equals weight); Hamiltonian cycle ≤p\le_p traveling salesperson (distances 1 and 2); vertex cover ≤p\le_p set cover (each element in two sets). It is the shortest proof and the first to try: is a special case of my problem a known problem?

Local replacement. Replace each element of the source instance with a fixed target piece. A long clause by a chain of three-literal clauses; a directed vertex by an undirected triplet; an undirected edge by a directed cycle of length 2 (from vertex cover to feedback vertex set in Karp’s map). Correctness is proved piece by piece.

Component design. When neither suffices, design gadgets with separate functions:

ReductionChoiceCheckConsistencyThreshold
3-SAT →\to independent setone vertex per clause (triangle)the chosen literal serves the clauseedges between opposite literalsk=mk = m
3-SAT →\to 3-coloringxix_i or ¬xi\neg x_i colored T\mathsf{T}OR gate with output joined to F and Btriangle xi,¬xi,Bx_i, \neg x_i, Bthree colors
3-SAT →\to Hamiltonian cyclerow directionclause vertex with detoureach row traversed in one directioncycle visits everything
3-SAT →\to subset sumviv_i or vi′v_i'clause digit with slackvariable digit =1= 1target TT

The scheme is always the same: choose a value per variable, check each clause, force the choice to be consistent, and set a threshold (a kk, a color, a target) attained only if all checks pass. The hard part is almost never checking but consistency: this is where the gadget must stop the choice from “cheating” (a detour that does not return to its row, a literal chosen both ways, a carry between digits).

Choosing the source. The best source usually has the same “shape” as your problem:

Your problem concerns…Natural source
choosing a subset with pairwise restrictions (conflicts)independent set, clique
covering something with few elementsvertex cover or set cover
assigning labels or colors with incompatibilities3-coloring, 3-SAT
a traversal visiting everything onceHamiltonian cycle
splitting numbers into equal groups (large values)partition, subset sum
splitting numbers into equal groups (small values)3-partition
logic with general constraints3-SAT

Checklist for a complete proof. Before accepting a proof, make these six checks: (a) Q∈NPQ \in \mathrm{NP}, with certificate and verifier; (b) source PP is NP-complete and not a disguised easy case (reducing 2-SAT or a special case of PP in P does not work); (c) ff is defined for every instance of PP, including degenerate cases (clauses with repeated literals, T>ST > S, edgeless graphs); (d) ff is polynomial in time and output size; (e) forward direction proved, with translated certificate; (f) reverse direction proved, with translated certificate. If you can run ff and a solver on small instances on both sides, do it: the analogue of a unit test (you will do this in the lab).

Practical problems that turn out to be NP-hard

The catalogue is not a museum. Some problems you will work with are NP-hard, explaining entire tools:

  • Optimal decision trees. Hyafil and Rivest (1976) proved building the optimal binary decision tree (one minimizing, for example, the expected number of questions) NP-complete. This is why ID3, CART and their descendants grow trees greedily: there is no shortcut to the global optimum (module 11).
  • K-means. It is NP-hard even in the plane (Mahajan, Nimbhorkar and Varadarajan, 2009), and also with k=2k = 2 in arbitrary dimension (Dasgupta, 2008; Aloise et al., 2009). Lloyd’s algorithm guarantees only a local optimum, and smart initializations (kk-means++) are an approximation measure, not exactness (module 12).
  • Package dependency resolution. Deciding whether an installation consistent with a package manager’s version constraints exists is NP-complete (Mancinelli et al., 2006); Russ Cox clearly explained it as “Version SAT” (2016). Modern managers incorporate SAT solvers or CDCL-like algorithms precisely for this reason (module 0).

These are not the only examples: Blum and Rivest (1992) proved that training a three-node neural network to fit data is NP-complete. In all these cases NP-hardness is a worst-case statement and does not prevent real instances from being tractable: see lesson 33.

Implementation from scratch

The best check of a reduction is to run it. The next cell implements the three main reductions (3-SAT to independent set, 3-coloring and subset sum) as functions generating instances, solves both sides by brute force or branching on small random formulas (plus a hand-made unsatisfiable one), and checks that answers agree and certificates translate in both directions. This is exactly what the checklist asks.

[ ]Executable and verified reductionsBrowser
import itertools, random, time

def rand_formula(n, m, rng):
    """m cláusulas de 3 literales (pueden repetirse variables); literal +i es x_i y -i es ¬x_i."""
    return [tuple(rng.choice((1, -1)) * rng.randint(1, n) for _ in range(3)) for _ in range(m)]

def sat_brute(n, clauses):
    for bits in itertools.product((False, True), repeat=n):
        if all(any(bits[abs(l) - 1] == (l > 0) for l in c) for c in clauses):
            return bits
    return None

# ---------- 3-SAT -> conjunto independiente ----------
def red_indep(clauses):
    m = len(clauses)
    lit = [l for c in clauses for l in c]                       # vértice v = 3j + p
    edges = {(3 * j + p, 3 * j + q) for j in range(m) for p, q in ((0, 1), (0, 2), (1, 2))}
    edges |= {(u, v) for u in range(3 * m) for v in range(u + 1, 3 * m)
              if u // 3 != v // 3 and lit[u] == -lit[v]}
    return 3 * m, edges, m, lit

def max_indep(nv, edges):
    """Conjunto independiente máximo por ramificación: o se toma el vértice de mayor grado o se descarta."""
    adj = {v: set() for v in range(nv)}
    for u, v in edges:
        adj[u].add(v); adj[v].add(u)
    best = []
    def rec(cand, chosen):
        nonlocal best
        if len(chosen) + len(cand) <= len(best):
            return
        if not cand:
            best = list(chosen); return
        v = max(cand, key=lambda x: len(adj[x] & cand))
        rec(cand - adj[v] - {v}, chosen + [v])               # tomar v
        rec(cand - {v}, chosen)                              # descartar v
    rec(set(range(nv)), [])
    return best

def assignment_from_indep(lit, S, n):
    a = [False] * n
    for v in S:
        a[abs(lit[v]) - 1] = lit[v] > 0
    return tuple(a)

def indep_from_assignment(clauses, a):
    return [3 * j + next(p for p, l in enumerate(c) if a[abs(l) - 1] == (l > 0)) for j, c in enumerate(clauses)]

# ---------- 3-SAT -> 3-coloración ----------
def red_color(n, clauses):
    """Vértices 0, 1, 2 = T, F, B; literal x_i = 3 + 2(i-1), ¬x_i = 4 + 2(i-1); luego 6 vértices por cláusula."""
    lit = lambda l: 3 + 2 * (abs(l) - 1) + (l < 0)
    E = [(0, 1), (0, 2), (1, 2)]
    for i in range(1, n + 1):
        E += [(lit(i), lit(-i)), (lit(i), 2), (lit(-i), 2)]
    nv = 3 + 2 * n
    for c in clauses:
        a, b, d = (lit(l) for l in c)
        x1, y1, o1, x2, y2, o2 = range(nv, nv + 6); nv += 6
        E += [(a, x1), (b, y1), (x1, y1), (x1, o1), (y1, o1), (o1, 2),               # OR(a, b) -> o1, con o1 != B
              (o1, x2), (d, y2), (x2, y2), (x2, o2), (y2, o2), (o2, 1), (o2, 2)]     # OR(o1, c) -> o2 = T
    return nv, E, lit

def colorear(nv, E, pre):
    """Backtracking con el vértice más restringido primero; `pre` fija colores de partida."""
    adj = [set() for _ in range(nv)]
    for u, v in E:
        adj[u].add(v); adj[v].add(u)
    col = {0: 0, 1: 1, 2: 2, **pre}
    def libres(v):
        return [c for c in range(3) if all(col.get(u) != c for u in adj[v])]
    def rec():
        pend = [v for v in range(nv) if v not in col]
        if not pend:
            return True
        v = min(pend, key=lambda x: len(libres(x)))
        for c in libres(v):
            col[v] = c
            if rec():
                return True
            del col[v]
        return False
    return dict(col) if rec() else None

# ---------- 3-SAT -> suma de subconjuntos ----------
def red_ssum(n, clauses):
    m, D = len(clauses), n + len(clauses)
    num = lambda digs: int("".join(map(str, digs)))
    nums, tag = [], []
    for i in range(1, n + 1):
        for sgn in (1, -1):
            d = [0] * D; d[i - 1] = 1
            for j, c in enumerate(clauses):
                d[n + j] = int(sgn * i in c)
            nums.append(num(d)); tag.append(("lit", sgn * i))
    for j in range(m):
        d = [0] * D; d[n + j] = 1
        nums += [num(d)] * 2; tag += [("slack", j)] * 2
    return nums, int("1" * n + "3" * m), tag

def subset_sum(nums, T):
    """Meet-in-the-middle: devuelve los índices de un subconjunto de suma T o None."""
    h = len(nums) // 2
    def sums(idx):
        out = {0: ()}
        for i in idx:
            for s, sub in list(out.items()):
                out.setdefault(s + nums[i], sub + (i,))
        return out
    A, B = sums(range(h)), sums(range(h, len(nums)))
    for s, sub in A.items():
        if T - s in B:
            return sub + B[T - s]
    return None

def ssum_from_assignment(n, clauses, tag, a):
    chosen = [k for k, t in enumerate(tag) if t[0] == "lit" and (t[1] > 0) == a[abs(t[1]) - 1]]
    for j, c in enumerate(clauses):
        verdaderos = sum(a[abs(l) - 1] == (l > 0) for l in set(c))
        chosen += [k for k, t in enumerate(tag) if t == ("slack", j)][: 3 - verdaderos]
    return chosen

# ---------- comprobación: fórmulas al azar y las tres reducciones ----------
rng = random.Random(28)
inst = [(3, [(1, 2, 2), (1, -2, -2), (-1, 2, 2), (-1, -2, -2)])]            # una insatisfacible a mano
inst += [(3, rand_formula(3, rng.randint(8, 12), rng)) for _ in range(15)]
cuenta = {"sat": 0, "insat": 0}
t0 = time.perf_counter()
for n, cl in inst:
    a = sat_brute(n, cl)
    nv, Ei, k, lit = red_indep(cl)
    S = max_indep(nv, Ei)
    nv2, Ec, litv = red_color(n, cl)
    pre = {litv(i if a[i - 1] else -i): 0 for i in range(1, n + 1)} if a else {}
    col = colorear(nv2, Ec, pre)
    nums, T, tag = red_ssum(n, cl)
    sub = subset_sum(nums, T)
    positiva = a is not None
    assert (len(S) >= k) == (col is not None) == (sub is not None) == positiva, (cl, positiva)
    if not positiva:
        cuenta["insat"] += 1
        continue
    cuenta["sat"] += 1
    # certificados en las dos direcciones
    S1 = indep_from_assignment(cl, a)
    assert len(S1) == k and not any(u in S1 and v in S1 for u, v in Ei)         # asignación -> independiente
    a2 = assignment_from_indep(lit, S[:k], n)
    assert all(any(a2[abs(l) - 1] == (l > 0) for l in c) for c in cl)           # independiente -> asignación
    a3 = tuple(col[litv(i)] == 0 for i in range(1, n + 1))                       # coloración -> asignación
    assert all(any(a3[abs(l) - 1] == (l > 0) for l in c) for c in cl)
    ch = ssum_from_assignment(n, cl, tag, a)                                     # asignación -> subconjunto
    assert sum(nums[i] for i in ch) == T
    a4 = tuple(any(tag[i] == ("lit", v) for i in sub) for v in range(1, n + 1))  # subconjunto -> asignación
    assert all(any(a4[abs(l) - 1] == (l > 0) for l in c) for c in cl)
print("fórmulas:", len(inst), cuenta, " | último caso:", nv, "vértices (IS),", nv2, "vértices (3-COL),", len(nums), "números de", len(str(T)), "dígitos")
print("todas las reducciones coinciden con la fuerza bruta y los certificados se traducen en los dos sentidos")

Notice three things. First, the triple assertion: the four answers (the formula and the three targets) must agree on every instance, including unsatisfiable ones, where half a reduction fails. Second, certificates: ssum_from_assignment is the forward direction of the proof (choose one number per variable and complete with slack) and reading sub is the reverse. Third, size: in the last output case (n=3n = 3, m=11m = 11), 3-coloring produces a graph with 3+6+66=753 + 6 + 66 = 75 vertices, and subset sum 28 numbers with 14 digits: a target of order 101310^{13}, for which DP is already impractical.

The boundary between weak and strong, in an experiment

The second lab makes the difference visible. We solve subset sum two ways: pseudopolynomial DP, using a Python integer as a bitset (bit ss indicates sum ss is reachable), and meet-in-the-middle (lesson 30), which generates all sums of each half and matches them, at cost O(2n/2)\bigO(2^{n/2}) independent of number size. We measure each cost by counting cells and sums, independent of the clock.

[ ]Hard instance factoryBrowser
import random, time

def dp_subset_sum(nums, T):
    """DP pseudopolinómica: un entero de Python hace de bitset (el bit s indica «la suma s es alcanzable»)."""
    reach, mask = 1, (1 << (T + 1)) - 1
    for a in nums:
        reach |= (reach << a) & mask
    return (reach >> T) & 1 == 1

def mitm_subset_sum(nums, T):
    """Meet-in-the-middle: todas las sumas de cada mitad y una búsqueda cruzada. Coste ~ 2^(n/2), sin depender de T."""
    h = len(nums) // 2
    def sums(a):
        out = [0]
        for x in a:
            out += [s + x for s in out]
        return out
    left, right = sums(nums[:h]), set(sums(nums[h:]))
    return any(T - s in right for s in left)

def instancia(n, bits, rng):
    """n enteros de a lo sumo `bits` bits y un objetivo alcanzable (suma de la mitad de ellos)."""
    nums = [rng.randrange(1, 1 << bits) for _ in range(n)]
    return nums, sum(nums[::2])

rng = random.Random(7)
n = 20
print(f"n = {n}: celdas de la DP (n·T) frente a sumas de MITM (2·2^(n/2) = {2 * 2 ** (n // 2)})")
print(f"{'bits':>5} {'celdas DP':>14}   misma respuesta")
for bits in (4, 8, 12, 16, 20):
    nums, T = instancia(n, bits, rng)
    r1, r2 = dp_subset_sum(nums, T), mitm_subset_sum(nums, T)
    print(f"{bits:>5} {n * (T + 1):>14,}   {r1 == r2 == True}")

# Números grandes: la DP ni cabe en memoria (haría falta un bitset de ~2^64 bits); MITM no se entera
nums, T = instancia(n, 64, rng)
print(f"\nn = {n}, 64 bits: la DP necesitaría ~{n * T:.2e} celdas; MITM responde {mitm_subset_sum(nums, T)}")

# Números pequeños: n = 60 con 10 bits. MITM necesitaría 2^31 sumas; la DP, 60·T celdas
nums, T = instancia(60, 10, rng)
print(f"n = 60, 10 bits: DP responde {dp_subset_sum(nums, T)} con {60 * (T + 1):,} celdas; MITM haría {2 ** 31:,} sumas")

# Densidad: qué fracción del rango [0, Σ] de objetivos es alcanzable (n = 16)
print("\ndensidad de sumas alcanzables, n = 16")
for bits in (4, 8, 12, 16, 20):
    nums = [rng.randrange(1, 1 << bits) for _ in range(16)]
    reach, S = 1, sum(nums)
    for a in nums:
        reach |= reach << a
    print(f"  {bits:>2} bits: {reach.bit_count() / (S + 1):6.1%} de los {S + 1:,} objetivos")

The table tells the whole story. For 4-bit numbers DP needs about 1380 cells, fewer than the 2048 MITM sums; for 8 bits it is already 2.2×1042.2 \times 10^4, and for 20 bits, 8×1078 \times 10^7. DP cost grows with the value of the numbers; MITM cost only with nn. In the second part the regions separate completely: with 64 bits DP is impossible and MITM still takes milliseconds, while with n=60n = 60 and 10 bits the reverse holds, 2312^{31} sums versus fewer than a million cells. Neither is polynomial in input size, but each exploits a kind of structure. Density completes the picture: with 4 bits all targets are reachable (the instance is “dense” and almost always positive), while with 20 bits only a small fraction are; real subset sum hardness lies in the intermediate region.

The library version

You need not write every solver. An integer linear program with binaries checks the independent-set reduction in one line of modeling, and the relationship with vertex cover comes for free: if τ(G)\tau(G) is the size of the smallest cover, α(G)+τ(G)=n\alpha(G) + \tau(G) = n. We add the first lab’s unsatisfiable formula to also see the α<m\alpha < m case.

[ ]An ILP as an independent-set oracleBrowser
import numpy as np
from scipy.optimize import milp, LinearConstraint, Bounds

def ilp_indep(nv, edges):
    """max sum x_v  sujeto a  x_u + x_v <= 1 en cada arista, x binaria."""
    A = np.zeros((len(edges), nv))
    for r, (u, v) in enumerate(sorted(edges)):
        A[r, u] = A[r, v] = 1
    res = milp(c=-np.ones(nv), constraints=LinearConstraint(A, ub=1), integrality=np.ones(nv), bounds=Bounds(0, 1))
    return int(round(-res.fun))

def ilp_cover(nv, edges):
    """min sum x_v  sujeto a  x_u + x_v >= 1 en cada arista, x binaria."""
    A = np.zeros((len(edges), nv))
    for r, (u, v) in enumerate(sorted(edges)):
        A[r, u] = A[r, v] = 1
    res = milp(c=np.ones(nv), constraints=LinearConstraint(A, lb=1), integrality=np.ones(nv), bounds=Bounds(0, 1))
    return int(round(res.fun))

rng2 = random.Random(5)
for n, cl in [inst[0]] + [(3, rand_formula(3, rng2.randint(8, 12), rng2)) for _ in range(4)]:
    nv, Ei, k, lit = red_indep(cl)
    a_ilp, tau = ilp_indep(nv, Ei), ilp_cover(nv, Ei)
    a_bb = len(max_indep(nv, Ei))
    print(f"m = {len(cl):2d}: α(ILP) = {a_ilp}, α(ramificación) = {a_bb}, τ(ILP) = {tau}, α + τ = {a_ilp + tau} = 3m = {nv};  satisfacible: {sat_brute(n, cl) is not None}, α = m: {a_ilp == k}")

In a real solver, the model is the reduction: the gadgets you just wrote translate a problem into a format (SAT, ILP, SMT) an industrial solver can tackle. This is the highest-value use of all this material: when an NP-complete problem appears in production, reduce it to SAT or ILP and let years of solver engineering do the work (lesson 30).

Typical mistakes

Exercises

QuizThe direction of a reduction
You want to prove your problem QQ NP-hard and already know Hamiltonian cycle (HC) is. What should you construct?
Proof3-SAT to independent set, in both directions
Prove: Let φ\varphi be a 3-CNF formula with mm clauses and GφG_\varphi the graph from the lesson (one triangle per clause and an edge between each literal and its negation in different clauses). Then φ\varphi is satisfiable if and only if GφG_\varphi has an independent set of size mm.
0
Prove both implications: from an assignment to a set, and from a set to an assignment.

Step 1 of 4. Forward: given an assignment aa satisfying φ\varphi, what set do you construct?

Proof3-coloring is NP-complete: complete the gadget
Prove: With the lesson's gadget, a 3-CNF φ\varphi is satisfiable if and only if graph Gφ′G'_\varphi is 3-colorable. Complete the proof that the clause gadget (two OR gates chained, o1o_1 joined to BB and o2o_2 joined to FF and BB) admits a coloring exactly when some input is T\mathsf{T}.
0
Assume all three inputs are colored T\mathsf{T} or F\mathsf{F}.

Step 1 of 4. With a=b=Fa = b = \mathsf{F}, what color is o1o_1 and why?

ProofVertex cover is NP-complete
Prove: Prove that deciding whether a graph GG with nn vertices has a vertex cover of size at most kk is NP-complete, by reduction from independent set.
0
We know independent set (deciding whether an independent set of size at least kk exists) is NP-complete.

Step 1 of 4. Membership in NP: what certificate and verifier do you use?

QuizChoosing the source: two servers
You must prove the following problem NP-hard: ‘given nn jobs with integer durations did_i (up to 10910^9 seconds), can they be distributed between two identical servers so that they finish at exactly the same time?’ Which source is most natural?
QuizChoosing the source: security cameras
‘Given a campus street map and an integer kk, can kk cameras be placed at intersections so that each street has a camera at one of its endpoints?’ Which NP-complete problem is suitable to reduce?
QuizChoosing a source for strong hardness
You want to prove bin packing (do nn items with integer sizes sis_i fit in kk bins of capacity BB?) strongly NP-hard. Which source is suitable?
QuizStrong or weak?
Which of these problems cannot be strongly NP-hard unless P=NP\mathrm{P} = \mathrm{NP}?
NumericSize of the 3-coloring graph
You apply the reduction from 3-SAT to 3-coloring to a formula with n=5n = 5 variables and m=8m = 8 clauses. How many vertices does the graph have?
NumericEdges in the independent-set graph
Let φ=(x1∨x2∨x3)(¬x1∨¬x2∨x3)(x1∨¬x2∨¬x3)(¬x1∨x2∨¬x3)\varphi = (x_1 \lor x_2 \lor x_3)(\neg x_1 \lor \neg x_2 \lor x_3)(x_1 \lor \neg x_2 \lor \neg x_3)(\neg x_1 \lor x_2 \lor \neg x_3). How many edges in total does the reduction graph GφG_\varphi have?
NumericHow many bits does the target have?
The reduction from 3-SAT to subset sum, applied to a formula with n=4n = 4 variables and m=6m = 6 clauses, has target T=1111333333T = 1111333333 (four ones and six threes). How many bits does TT need in binary (minimum length)?
NumericThe number added by the partition reduction
You reduce subset sum a=(4,7,9,10)a = (4, 7, 9, 10), T=13T = 13 to partition by adding x=S+Tx = S + T and y=2S−Ty = 2S - T. What is yy?
CodeFrom subset sum to partition
Implement ssum_a_particion(a, T), which receives a list of positive integers a and a target T and returns an integer list for the equivalent partition instance: the list has a partition (two equal-sum groups) if and only if some subset of a sums to T. If T < 0 or T > sum(a), return [1] (a fixed negative instance). Do not modify a.
def ssum_a_particion(a, T):
  """Devuelve una lista de enteros con partición si y solo si algún subconjunto de a suma T."""
  S = sum(a)
  # tu código: casos fuera de rango, y los dos números que se añaden
  return list(a)
Shift+Enter to run

Summary

Key idea
Proving NP-completeness is designing a translation: choose an NP-complete source with the same shape as the problem, construct choice, checking and consistency gadgets, and prove the answer is preserved in both directions; exponential numbers give weak hardness, bounded ones give strong hardness.
  • Five obligations per proof: membership in NP, NP-complete source, polynomial construction, forward and reverse. Reducing backwards or proving only one direction is the classic error.
  • 3-SAT is the universal source: fixed-size clauses. 2-SAT is in P (implication graph and strongly connected components); the boundary is between 2 and 3 literals.
  • Independent set: a triangle per clause and edges between opposite literals, with k=mk = m; α(Gφ)\alpha(G_\varphi) counts satisfiable clauses. Clique and vertex cover follow by complementation.
  • 3-coloring: palette, variable and OR gate with output forced to T. Hamiltonian cycle: one ladder per variable whose direction is its value, and a clause vertex with a detour; traveling salesperson is a special case with distances 1 and 2.
  • Subset sum: decimal digits without carries and slack numbers; partition with numbers S+TS + T and 2S−T2S - T. The n+mn + m-digit numbers explain weak hardness (pseudopolynomial DP); 3-partition, traveling salesperson and bin packing are strong.
  • Patterns: restriction, local replacement and components. The difficult part is always consistency. Optimal decision trees, kk-means and dependency resolution are NP-hard: hence greedy algorithms, Lloyd and solvers.