Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

A Gallery of NP-Completeness Reductions

From 3-SAT to independent set, vertex cover, Hamiltonian cycle and subset sum.

Once one problem is known to be NP-complete, proving the next is a matter of construction: build gadgets that make one problem impersonate another, then prove that nothing is gained or lost in translation. Karp did it 21 times in one 1972 paper, and NP-completeness turned from a curiosity about logic into the map of hard problems.

What you’ll learn

  • Follow the recipe for an NP-completeness proof, and avoid its classic mistakes, starting with the direction of the reduction.
  • Prove that independent set, vertex cover and clique reduce to one another, and that 3-SAT reduces to 3-coloring through gadgets.
  • Reduce 3-SAT to subset sum with decimal digits, and explain weak versus strong NP-hardness.
  • Sketch the reduction from vertex cover to Hamiltonian cycle, and prove that Hamiltonian cycle reduces to the traveling salesman, which therefore has no constant-factor approximation unless P = NP.

The recipe, and Karp’s 21

Every proof that a problem BB is NP-complete follows the same five steps.

  1. BB is in NP. Name the certificate and the polynomial-time check.
  2. Choose a known NP-complete problem AA whose structure resembles BB: 3-SAT for choices under constraints, vertex cover or independent set for selections in graphs, subset sum or partition for numbers, Hamiltonian cycle for orderings.
  3. Construct a map ff from instances of AA to instances of BB, computable in polynomial time. Watch the size of what you build, and how its numbers are written.
  4. Prove x∈A⇒f(x)∈Bx \in A \Rightarrow f(x) \in B, usually by carrying a certificate of xx forward.
  5. Prove f(x)∈B⇒x∈Af(x) \in B \Rightarrow x \in A. This is usually the hard direction: every solution of the built instance, including ones you did not intend, must decode into a solution of xx. Gadgets exist to force solutions into the intended shape.

Karp's 1972 paper applied the recipe to 21 problems: satisfiability, 0–1 integer programming, clique, set packing, vertex cover, set covering, feedback vertex set, feedback arc set, directed and undirected Hamiltonian cycle, satisfiability with at most three literals per clause, chromatic number, clique cover, exact cover, hitting set, Steiner tree, 3-dimensional matching, knapsack, job sequencing, partition and max cut. Garey and Johnson (1979) later singled out six "basic" NP-complete problems as the usual starting points (3-SAT, 3-dimensional matching, vertex cover, clique, Hamiltonian cycle and partition) and cataloged hundreds more.

Check your understanding

You find a polynomial-time reduction from your problem PP to 3-SAT. What have you shown?

  1. That PP is NP-hard
  2. That PP is in NP, so a SAT solver can decide it after translation, but nothing about how hard PP is
  3. That PP is NP-complete
  4. That PP is in P
Show the answer

B. That PP is in NP, so a SAT solver can decide it after translation, but nothing about how hard PP is

P≤p3-SATP \le_p \text{3-SAT} says PP is no harder than 3-SAT. Since NP is closed under polynomial-time reductions, PP is in NP, and translating then calling a SAT solver decides it. Easy problems reduce to 3-SAT too; hardness needs the opposite direction.

Graphs: independent set, vertex cover, clique and 3-coloring

DerivationProof
  1. {u,v}⊆S  ⟺  uv is not covered by V∖S\{u, v\} \subseteq S \iff uv \text{ is not covered by } V \setminus S

    Independent set and vertex cover. An edge has both ends in SS exactly when it has no end in V∖SV \setminus S:

  2. uv∉E  ⟺  uv∈E(G‾)(u≠v)uv \notin E \iff uv \in E(\overline{G}) \qquad (u \ne v)

    Independent set and clique. Two vertices of SS are non-adjacent in GG exactly when they are adjacent in G‾\overline{G}:

  3. IS  ≤p  VC,IS  ≤p  CLIQUE,and back\text{IS} \;\le_p\; \text{VC}, \qquad \text{IS} \;\le_p\; \text{CLIQUE}, \qquad \text{and back}

    Cost. The maps (G,k)↦(G,n−k)(G, k) \mapsto (G, n - k) and (G,k)↦(G‾,k)(G, k) \mapsto (\overline{G}, k) take O(n2)O(n^2) time.

DerivationProof
  1. {col(vi), col(vˉi)}  =  {T,F}\{\mathrm{col}(v_i),\ \mathrm{col}(\bar v_i)\} \;=\; \{T, F\}

    Colors get names. In any 3-coloring the palette triangle uses all three colors; call them TT, FF and BB after its vertices. Each viv_i and vˉi\bar v_i is adjacent to BB and to each other, so one is colored TT and the other FF. Read xix_i as true exactly when viv_i is colored TT:

  2. u=w=F⇒o=F,u=T or w=T⇒o=T is possibleu = w = F \Rightarrow o = F, \qquad u = T \text{ or } w = T \Rightarrow o = T \text{ is possible}

    The OR-gadget lemma. If both inputs are colored FF, then xx and yy avoid FF, so they take TT and BB and force o=Fo = F. If at least one input is colored TT, the gadget can be colored with o=To = T: for inputs (T,F)(T, F) use x=Fx = F, y=By = B; for (F,T)(F, T) use x=Bx = B, y=Fy = F; for (T,T)(T, T) use x=Fx = F, y=By = B.

  3. a=b=c=F  ⟹  o1=F  ⟹  o2=F, a contradictiona = b = c = F \;\Longrightarrow\; o_1 = F \;\Longrightarrow\; o_2 = F, \text{ a contradiction}

    Colorable gives satisfiable. If some clause had all three literals false, its literal vertices would all be colored FF; the lemma forces o1=Fo_1 = F, then o2=Fo_2 = F, but o2o_2 is adjacent to the palette vertex FF. So every clause has a true literal.

  4. some literal T  ⟹  o2=T is possible\text{some literal } T \;\Longrightarrow\; o_2 = T \text{ is possible}

    Satisfiable gives colorable. Color the palette, then viv_i with TT and vˉi\bar v_i with FF when xix_i is true, the reverse otherwise. In each clause, if aa or bb is true, color the first gadget with o1=To_1 = T; otherwise o1=Fo_1 = F is forced and cc is true. Either way the second gadget has an input colored TT, so it can be colored with o2=To_2 = T, which its edges to FF and BB allow.

Gadgets are where reductions break, so check them by machine. Exhaustive search confirms that the clause gadget can be completed for exactly 7 of the 8 truth patterns of its literals, all but all-false, and that the whole reduction agrees with a brute-force 3-coloring search on 300 random formulas, 33 of them unsatisfiable.

Numbers: subset sum, and weak versus strong hardness

Subset sum asks whether some of the given positive integers add up exactly to a target tt. To reduce 3-SAT to it, write numbers in base 10 with one digit per variable and one per clause, n+mn + m digits in all:

  • for each variable xix_i, a number yiy_i ("xix_i true") with a 1 in digit xix_i and in the digit of every clause containing xix_i, and a number ziz_i ("xix_i false") with a 1 in digit xix_i and in the digit of every clause containing ¬xi\neg x_i;
  • for each clause, two slack numbers with a single 1 in that clause's digit;
  • the target t=1⋯1 3⋯3t = 1\cdots1\,3\cdots3: a 1 in every variable digit and a 3 in every clause digit.
Numberx1x_1x2x_2x3x_3C1C_1C2C_2
y1y_110010
z1z_110001
y2y_201010
z2z_201001
y3y_300111
z3z_300100
slacks for C1C_1 (two)00010
slacks for C2C_2 (two)00001
target11133
For (x1∨x2∨x3)∧(¬x1∨¬x2∨x3)(x_1 \lor x_2 \lor x_3) \land (\neg x_1 \lor \neg x_2 \lor x_3), read each row as a five-digit number. The assignment x1x_1 true, x2x_2 and x3x_3 false picks y1+z2+z3=10010+1001+100=11111y_1 + z_2 + z_3 = 10010 + 1001 + 100 = 11111; each clause has one true literal, so all four slack numbers are added, 10+10+1+110 + 10 + 1 + 1, reaching 1113311133.
DerivationProof
  1. every column sum  ≤  5  <  10\text{every column sum} \;\le\; 5 \;<\; 10

    No carries. A variable column receives at most 2 (from yiy_i and ziz_i), and a clause column at most 3 from literal numbers plus 2 from its slacks. Since 5<105 < 10, a subset reaches tt exactly when every column reaches its digit of tt:

  2. 1  ≤  #{true literals in Cj}  ≤  3⟹slacks fill the column to 31 \;\le\; \#\{\text{true literals in } C_j\} \;\le\; 3 \quad\Longrightarrow\quad \text{slacks fill the column to } 3

    Satisfiable gives a subset. Take yiy_i for every true xix_i and ziz_i for every false one: each variable column sums to 1, and each clause column to the number of true literals in its clause, between 1 and 3. Add 2, 1 or 0 of that clause's slack numbers to reach 3.

  3. column Cj=3,  slacks≤2  ⟹  Cj has a true literal\text{column } C_j = 3,\ \ \text{slacks} \le 2 \;\Longrightarrow\; C_j \text{ has a true literal}

    A subset gives a satisfying assignment. Each variable column must sum to exactly 1, so the subset contains exactly one of yiy_i and ziz_i: that is an assignment. Each clause column must reach 3 with at most 2 from slacks, so some chosen literal number has a 1 there, and its literal is true.

  4. input length O((n+m)2),values up to 10 n+m\text{input length } O\big((n + m)^2\big), \qquad \text{values up to } 10^{\,n+m}

    Size. There are 2n+2m2n + 2m numbers of n+mn + m digits, O((n+m)2)O((n + m)^2) digits in all, so the construction is polynomial. The values, though, are as large as 10n+m10^{n+m}, which matters next.

python
import itertools, random

def sat_to_subset_sum(clauses, n):
    """Base-10 digits: one per variable, then one per clause. Returns (numbers, target)."""
    m = len(clauses)
    def number(var, clause_digits):
        d = [0] * (n + m)
        if var:
            d[var - 1] = 1
        for j in clause_digits:
            d[n + j] += 1
        return int(''.join(map(str, d)))
    nums = []
    for i in range(1, n + 1):
        nums.append(number(i, [j for j, c in enumerate(clauses) if i in c]))    # y_i: x_i true
        nums.append(number(i, [j for j, c in enumerate(clauses) if -i in c]))   # z_i: x_i false
    for j in range(m):
        nums += [number(0, [j]), number(0, [j])]                                # two slacks per clause
    return nums, int('1' * n + '3' * m)

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

def reachable_sums(nums):
    sums = {0}
    for x in nums:
        sums |= {s + x for s in sums}
    return sums

print(sat_to_subset_sum([[1, 2, 3], [-1, -2, 3]], 3))   # ([10010, 10001, 1010, 1001, 111, 100, 10, 10, 1, 1], 11133)
random.seed(2)
for _ in range(2000):
    n, m = random.randint(1, 3), random.randint(1, 5)
    F = [[random.choice([1, -1]) * random.randint(1, n) for _ in range(3)] for _ in range(m)]
    nums, t = sat_to_subset_sum(F, n)
    assert satisfiable(F, n) == (t in reachable_sums(nums))
print("agrees with brute force on 2,000 random formulas")

The 2,000 random formulas include 67 unsatisfiable ones, so both directions of the proof are tested.

Subset sum has an O(nt)O(nt) dynamic program: polynomial in the value of the target but exponential in its number of digits, a pseudo-polynomial algorithm. The reduction above needs exponentially large values, and it has to: when every number is bounded by a polynomial in nn, subset sum is in P. Problems like this are weakly NP-hard. One extra number also reduces subset sum to partition (split a set into two halves of equal sum): add ∣S−2t∣\abs{S - 2t}, where SS is the total of the numbers.

A problem is strongly NP-hard if it stays NP-hard when all its numbers are bounded by a polynomial in the input size (Garey & Johnson, 1978). Bin packing and 3-partition are, and so is the traveling salesman, whose hardness proof below uses only small weights. Unless P = NP, strongly NP-hard problems have no pseudo-polynomial algorithms; the lesson Pseudo-Polynomial Time develops the distinction.

Tours: Hamiltonian cycle and the traveling salesman

Vertex cover to Hamiltonian cycle needs a cleverer gadget (the version given by Garey & Johnson and by Cormen et al.). Each edge uvuv of GG becomes 12 vertices in two rows of six, one row for uu and one for vv, cross-linked so that a cycle visiting all 12 can pass through in exactly three ways: along uu's row alone (crossing over to vv's row and back), along vv's row alone, or along both rows separately. For each vertex ww, the gadgets of ww's edges are chained along ww's rows, and kk extra selector vertices are joined to the two ends of every chain. A Hamiltonian cycle then makes kk chain traversals, one per selector, and it reaches every gadget exactly when every edge has an endpoint among the chosen vertices: the cycle exists if and only if GG has a vertex cover of size kk.

DerivationProof
  1. OPT  =  n\mathrm{OPT} \;=\; n

    A Hamiltonian cycle is a tour of cost nn. Following it uses nn edges of weight 1, and no tour has fewer than nn legs:

  2. cost  ≥  (n−1)+ρn+1  =  (ρ+1) n  >  ρn\text{cost} \;\ge\; (n - 1) + \rho n + 1 \;=\; (\rho + 1)\,n \;>\; \rho n

    Without one, every tour uses a non-edge. A tour with all nn legs in GG would be a Hamiltonian cycle, so some leg costs ρn+1\rho n + 1:

  3. ALG≤ρ OPT=ρn  ⟺  G is Hamiltonian\text{ALG} \le \rho\,\mathrm{OPT} = \rho n \iff G \text{ is Hamiltonian}

    Hardness and inapproximability. With ρ=1\rho = 1, asking "is there a tour of cost at most nn?" decides Hamiltonian cycle. For any ρ\rho, a ρ\rho-approximation returns a tour of cost at most ρn\rho n exactly when GG has a Hamiltonian cycle, so comparing its answer with ρn\rho n decides the question. The weights have O(log⁡(ρn))O(\log(\rho n)) bits, so the construction is polynomial.

  4. w(u,v)=ρn+1  >  2  =  w(u,x)+w(x,v)w(u, v) = \rho n + 1 \;>\; 2 \;=\; w(u, x) + w(x, v)

    Why metric TSP escapes. These weights violate the triangle inequality: two edges of weight 1 make a detour of cost 2 around a non-edge of weight ρn+1\rho n + 1. Weights 1 and 2 are metric, so metric TSP is still NP-hard, but it can be approximated within 1.5 (the lesson Approximating the Traveling Salesman).

Key takeaways

  • An NP-completeness proof shows membership in NP, then reduces a known NP-complete problem to the new one in polynomial time, proving both directions and watching the size of the construction and the encoding of its numbers.
  • Complements tie independent set, vertex cover and clique together, and gadgets (a palette triangle, complementary variable pairs, OR-gadgets) carry 3-SAT into 3-coloring.
  • Decimal digits without carries carry 3-SAT into subset sum, but only with exponentially large values: subset sum is weakly NP-hard, with a pseudo-polynomial DP, while strongly NP-hard problems such as bin packing stay hard with small numbers.
  • Weights 1 and ρn+1\rho n + 1 turn Hamiltonian cycle into the traveling salesman: TSP is NP-hard and has no constant-factor approximation unless P = NP. The triangle inequality is exactly what metric TSP adds.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A graph on 10 vertices has a largest independent set of size 4. What is the size of its smallest vertex cover?

  1. 4
  2. 6
  3. 10
  4. 14
Show the answer

B. 6

SS is independent exactly when V∖SV \setminus S is a vertex cover, so the smallest cover is the complement of the largest independent set: 10−4=610 - 4 = 6.

Question 2

In the reduction from 3-SAT to subset sum, why does writing the numbers in base 10 work?

  1. Because subset sum is defined for decimal numbers
  2. Because every column sums to at most 5, so no carry mixes columns and the target can only be met column by column
  3. Because base 10 keeps the numbers small
  4. It is arbitrary: base 2 would work just as well
Show the answer

B. Because every column sums to at most 5, so no carry mixes columns and the target can only be met column by column

A clause column gets at most 3 from literal numbers and 2 from its slack numbers, a variable column at most 2. Any base of at least 6 keeps the columns independent; 10 is just convenient.

Question 3

Which problem stays NP-hard even when every number in the input is bounded by a polynomial in the input size?

  1. Subset sum
  2. 0/1 knapsack
  3. Partition
  4. Bin packing
Show the answer

D. Bin packing

Bin packing, like 3-partition, is strongly NP-hard. The other three have pseudo-polynomial dynamic programs, O(nT)O(nT) or O(nW)O(nW), which run in polynomial time once the numbers are polynomially bounded.

Question 4

The reduction from Hamiltonian cycle shows that general TSP has no polynomial-time ρ\rho-approximation for any constant ρ\rho, unless P = NP. Why does the argument fail for metric TSP?

  1. Metric instances are always small
  2. The weights it builds, 1 and ρn+1\rho n + 1, violate the triangle inequality
  3. Hamiltonian cycle is easy when distances are metric
  4. Metric TSP can be solved exactly in polynomial time
Show the answer

B. The weights it builds, 1 and ρn+1\rho n + 1, violate the triangle inequality

Two edges of weight 1 make a detour of cost 2, while the direct non-edge costs ρn+1\rho n + 1: the triangle inequality fails. With it, approximations exist, such as Christofides's algorithm, within a factor 1.5.

Further reading

  • R. M. Karp, "Reducibility among combinatorial problems," in R. E. Miller & J. W. Thatcher (eds.), Complexity of Computer Computations (Plenum, 1972), 85–103.
  • M. R. Garey & D. S. Johnson, Computers and Intractability: A Guide to the Theory of NP-Completeness (W. H. Freeman, 1979).
  • M. R. Garey & D. S. Johnson, "'Strong' NP-completeness results: motivation, examples, and implications," Journal of the ACM 25(3) (1978).
  • T. J. Schaefer, "The complexity of satisfiability problems," Proceedings of STOC (1978).
  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 34.