NP-Completeness

To check a proposed answer to this 10-variable formula, you test its 36 clauses once. To find the answer by trying, you test 932 of its 1,024 assignments, and the count doubles with each new variable. Nobody knows if finding must always be this much harder than checking.

Pick a formula size and press Run. The searcher tries assignments one at a time; the checker tests one given answer. Then we build, piece by piece: decision problems, the class P, certificates and NP, reductions, Cook-Levin, and the chain of reductions from SAT to the traveling salesman.

You need Big-O notation, graphs and a little Python. We build the rest from zero.

Based on Chapter 34 of Introduction to Algorithms (CLRS, third edition) by Cormen, Leiserson, Rivest and Stein. It builds on Chapter 22, Graph Algorithms, and leads to Chapter 35, Approximation Algorithms. The explanations, toy instances and devices are our own.

Find an answer, or check one

Illustrative. Each formula is random, with three literals per clause. We add clauses until exactly one assignment, a planted one, satisfies it. The searcher tries assignments in counting order and stops at the first that works. Each try also costs up to one check per clause, so the real gap is wider than the grid shows.

Chapter 0

Hard to Find, Easy to Check

Count the routes a delivery driver must try, and see why a faster computer barely helps

A driver leaves the depot, visits every stop once and comes home. She wants the shortest loop. Someone hands her a loop and claims it is under 80 km. She adds up the legs and knows in seconds. Finding the shortest loop is another matter.

How many loops are there? Name the number of places, the depot included, n. Name the number of different loops T.

Say it aloud

T equals n minus one, factorial, divided by two.

T
T the number of different loops through all n places.
(n − 1)!
n minus one factorial the orders of the n − 1 stops after the depot: (n − 1) × (n − 2) × … × 1.
/ 2
divided by two each loop appears twice, once in each direction.
In plain words

Start at the depot. Choose the order of the other n − 1 stops in every possible way. Halve the count, because a loop and its reverse are the same loop. The result is T.

With numbers

With n = 5: 4! = 24 orders, so T = 12 loops. With n = 20: T = 19!/2, about 6.1 × 1016. At a billion loops a second that is 6.1 × 107 seconds, about 1.9 years.

Checking one loop costs n additions and one comparison. Finding the best by trying costs T loops. Drag n and watch the two kinds of growth part.

Grow the problem

Each bar is a step count on a log scale: one tick is ten times more. Drag the number of places.

15

Times assume a billion steps a second. The 2n n2 bar is the step count of the Held-Karp dynamic program (1962), an exact method that is still exponential.

At n = 15 the loop count is 4.4 × 1010, which takes 44 seconds. At n = 25 it is 3.1 × 1023, about 9.8 million years. Sorting 25 numbers takes about 116 comparisons.

The failure. Symptom: a route planner passes its tests with 10 stops and hangs with 20. Measure: compute T before you run, then multiply by the time per loop. Fix: an exact method that is smarter than trying every loop, or a fast method with a known error bound (Chapter 9).

Many problems share this shape: a proposed answer is quick to check, but nobody knows a fast way to find one. This chapter of CLRS gives that shape a name, a test, and a family tree.

The road

  1. Decision problems and P: yes or no questions, and what counts as fast.
  2. NP: answers that come with a quick check.
  3. Reductions: turn one problem into another.
  4. NP-complete: the hardest problems in NP, and the first one.
  5. SAT to 3-SAT: cut long clauses into clauses of three.
  6. 3-SAT to clique: a formula becomes a graph.
  7. The chain: clique, vertex cover, Hamiltonian cycle, TSP.
  8. Subset sum: when the numbers are the problem.
  9. Coping: exact, approximate and heuristic tours.
  10. Field guide: what is proven, what is believed, the code.
Brute force on 20 places takes about 1.9 years. A computer 1,000 times faster arrives. About how many places can it finish in the same time?

Chapter 1

Decision Problems and the Class P

Ask yes or no questions, recover the best answer from them, and draw the line at polynomial time

"What is the shortest loop?" is an optimization problem: it asks for a best value. "Is there a loop of length at most 80?" is a decision problem: its answer is yes or no. One input to a problem is an instance. The theory of this chapter uses decision problems only.

Does that lose anything? No. Suppose a box answers "is there a loop of length at most k?" for any k you choose. Ask with k in the middle of the possible range. A yes halves the range from above, a no from below. Repeat until one value is left.

Ask the yes or no box

The shortest length is hidden somewhere from 0 to 100. Set k and ask, or let the device halve the range for you.

50

Illustrative. The hidden shortest length is 37.

A range of 101 values needs 7 questions, because 27 = 128 is the first power of two above 101. If lengths go up to a number U, about log2 U questions are enough. Writing U in binary takes about log2 U bits, so the number of questions grows with the size of the input. A fast decision box gives a fast optimizer.

What counts as fast

The input size n is the number of bits needed to write the instance. An algorithm runs in polynomial time if its steps are at most c · nk for some fixed numbers c and k. P is the class of decision problems that some polynomial-time algorithm solves.

Decision problemIn P?How
Is there an s to t path of weight at most k?YesDijkstra (Chapter 24)
Do 2 colours suffice to colour the graph?YesBreadth-first search, test for odd cycles
Is n prime?YesAKS test (2002)
Does the graph have a loop through every vertex once?Not knownNo polynomial algorithm is known

Why polynomial? A polynomial-time algorithm that calls a polynomial-time subroutine a polynomial number of times stays polynomial. Exponential growth has no such safety. At n = 1,000, n3 is 109 steps, about one second. At n = 100, 2n is about 1.3 × 1030.

The failure. Symptom: an algorithm that takes T steps for a target number T looks polynomial, then stalls on a 64-bit target. Measure: state the running time in bits of input, not in the values. Fix: call it pseudo-polynomial (Chapter 8), and plan for large numbers.

Loop lengths are whole numbers from 0 to 1,000. With a yes or no box for "is there a loop of length at most k?", how many questions always find the shortest length?

Chapter 2

NP: Answers You Can Check

Build a proposed loop through a graph, run the checker on it, and define NP from that check

A Hamiltonian cycle is a loop that visits every vertex of a graph exactly once. Does this 8-vertex graph have one? Finding out by trying means testing up to 7!/2 = 2,520 loops. But if a friend hands you a loop, you can check it at once.

Hand the checker a loop

Click vertices one after another to build a proposed loop. The checker tests it as you go.

A made-up graph with 12 edges. It has exactly 2 Hamiltonian cycles among its 2,520 possible loops.

The proposed loop is a certificate: evidence that the answer is yes. The program that tests it is a verifier. Here it runs two checks: each of the 8 vertices appears once, and each of the 8 steps, the closing step included, follows an edge. That is 16 checks, not 2,520 loops.

Call the instance x and its length in bits |x|. Call the certificate y. Call the verifier A: it reads x and y and outputs 1 for "accept" or 0. A decision problem L is in NP when such a verifier exists, runs in polynomial time, and works like this:

Say it aloud

x is in L if and only if there exists a y, with the length of y at most c times the length of x to the k, such that A of x and y equals one.

x ∈ L
x is in L the answer for instance x is yes.
∃ y
there exists a y some certificate works. One is enough.
|y| ≤ c|x|k
the length of y is at most c times the length of x to the k the certificate is short: polynomial in the input size, for fixed c and k.
A(x, y) = 1
A of x and y equals one the polynomial-time verifier accepts.
In plain words

For every yes instance x, some short certificate y makes A accept. For every no instance, no certificate y makes A accept.

With numbers

For the 8-vertex graph, y is a list of 8 vertex names, 3 bits each: 24 bits. A makes 16 checks. The loop 0, 1, 5, 4, 7, 6, 3, 2 passes all 16, so A(x, y) = 1 and x is a yes instance.

Every problem in P is in NP: the verifier ignores y and solves x itself. So P ⊆ NP. Whether the two classes are equal is open. The name NP means "nondeterministic polynomial time": a machine that could guess y would then check it in polynomial time.

No instances are another matter. For "this graph has no Hamiltonian cycle", nobody knows a short certificate. Problems whose no answers have short certificates form co-NP. Whether NP equals co-NP is also open.

The failure. Symptom: a verifier accepts 0, 1, 2, 3, 4, 5, 6, 7, a path with no edge from 7 back to 0. Measure: feed it known bad certificates: a repeat, a missing vertex, a missing closing edge. Fix: test all n steps, the closing step included.

Which statement places a decision problem in NP?

Chapter 3

Reductions: One Problem Dressed as Another

Translate an independent set question into a vertex cover question and see the answers always match

You run a radio network. Two stations joined by an edge interfere. Can you switch on k stations with no two joined? A set of vertices with no edge inside it is an independent set. Your colleague owns a fast program for another problem: a vertex cover is a set of vertices that touches every edge. Can her program answer your question?

Yes. Pick a set S. An edge inside S is an edge that misses everything outside S. So S is independent exactly when the rest, V − S, touches every edge.

Pick a set, read both answers

Click vertices to add them to S (blue). A pink ring marks the rest, V − S. An edge inside S turns red.

A made-up graph with 7 vertices and 9 edges. Its largest independent set has 3 vertices; its smallest vertex cover has 4.

That is a reduction. Name your problem A and hers B. Name the translating function f. A is polynomial-time reducible to B, written A ≤P B, when f runs in polynomial time and

Say it aloud

x is in A if and only if f of x is in B.

x ∈ A
x is in A instance x of problem A has answer yes.
f(x)
f of x the instance of B that the polynomial-time translation builds from x.
∈ B
is in B that new instance has answer yes for problem B.
In plain words

Translate x into f(x). A yes for x must become a yes for f(x), and a no must become a no. Then B's answer on f(x) is A's answer on x.

With numbers

x is (G, k = 3): "does G have an independent set of 3?" f(x) is (G, 7 − 3 = 4): "does G have a vertex cover of 4?" S = {A, D, G} is independent, and its rest {B, C, E, F} covers all 9 edges. Both answers are yes.

A reduction works in two directions. If B has a fast algorithm, so does A: translate, then solve. Say f takes n2 steps, and B's solver takes m3 steps on an instance of size m. The total is at most n2 + (n2)3 = n2 + n6, still polynomial. And if A has no fast algorithm, B cannot have one either.

The failure. Symptom: a "proof" that a new problem X is hard shows X ≤P SAT. That only says X is no harder than SAT. Measure: read the arrow: the known hard problem must sit on the left. Fix: reduce from the known hard problem to X.

A ≤P B, and someone finds a polynomial-time algorithm for B. What follows?

Chapter 4

NP-Complete: The Hardest Problems in NP

Define NP-completeness, then turn a logic circuit into clauses the way the first proof does

A problem L is NP-complete when L is in NP and every problem in NP reduces to L. A problem that meets only the second condition is NP-hard.

So if one NP-complete problem has a polynomial-time algorithm, every problem in NP has one, and P = NP. If one has none, none of them has one.

The first one

The first proof had to reduce every NP problem to one problem directly. Cook did it for satisfiability in 1971, and Levin did it on his own in 1973. CLRS goes through circuit satisfiability: does some input make a circuit of AND, OR and NOT gates output 1?

The idea: unroll the verifier's polynomial-time run into a circuit of polynomial size. Leave the certificate bits as free inputs. Some input makes the circuit output 1 exactly when some certificate makes the verifier accept.

Next, circuit satisfiability reduces to SAT: can the variables of a formula take values that make it true? Give every wire a variable. For every gate, write clauses that hold only when its output wire is right. A clause is an OR of literals, and a literal is a variable or its negation, written ¬a. For an AND gate with inputs a and b and output y:

Say it aloud

Not y or a, and not y or b, and y or not a or not b.

(¬y ∨ a)
not y or a if y is 1, then a must be 1.
(¬y ∨ b)
not y or b if y is 1, then b must be 1.
(y ∨ ¬a ∨ ¬b)
y or not a or not b if a and b are both 1, then y must be 1.
In plain words

The first two clauses stop y from claiming 1 when an input is 0. The third stops y from claiming 0 when both inputs are 1. Together they hold exactly when y equals a AND b.

With numbers

Take a = 1, b = 1, y = 0: the third clause reads 0 ∨ 0 ∨ 0, which is false, so the lie is caught. Take a = 1, b = 0, y = 0: the clauses read 1, 1, 1, all true. All 8 rows of the truth table pass this test.

Turn a circuit into clauses

Each button sets one wire to 1 or 0. Set the inputs, then try to lie on a gate wire. Watch which clause catches it.

A made-up circuit: y1 = x1 AND x2, y2 = NOT x3, out = y1 OR y2. The last clause, (out), demands output 1.

The circuit has 6 wires and 3 gates, so the formula has 6 variables and 3 + 2 + 3 + 1 = 9 clauses. Five of the 8 inputs make the output 1, and the formula has exactly 5 satisfying assignments: the gate clauses force every other wire.

The failure. Symptom: the formula and the circuit disagree. Measure: test each gate's clauses on its full truth table. Fix: keep all three AND clauses; without the third, y may sit at 0 when a = b = 1.

Tomorrow someone proves that 3-SAT, an NP-complete problem, has a polynomial-time algorithm. What follows?

Chapter 5

SAT to 3-SAT: Clauses of Three

Cut a long clause into a chain of three-literal clauses, linked by new variables

A formula in conjunctive normal form (CNF) is an AND of clauses. In 3-CNF every clause has exactly three literals. 3-SAT asks whether a 3-CNF formula is satisfiable. Its pieces are small and all the same shape, so most reductions start from it.

Why is 3-SAT still hard? Because any CNF formula can be rewritten in 3-CNF in polynomial time, without changing whether it is satisfiable. Take a long clause with k literals, l1 to lk. Add k − 3 new variables, y1 to yk−3, and write a chain:

Say it aloud

l-one or l-two or y-one, and not y-one or l-three or y-two, and so on, up to not y-k-minus-three or l-k-minus-one or l-k.

(l1 ∨ l2 ∨ y1)
l-one or l-two or y-one the first link: either l-one or l-two is true, or y-one passes the job on.
(¬y1 ∨ l3 ∨ y2)
not y-one or l-three or y-two a middle link: if the job comes in, l-three takes it or y-two passes it on.
(¬yk−3 ∨ lk−1 ∨ lk)
not y-k-minus-three or l-k-minus-one or l-k the last link: a job passed this far must end at one of the last two literals.
In plain words

Each y is a baton. Set yi to 1 to pass the job down the chain. If lj is true, pass the baton to the clause that holds lj, then drop it. If no literal is true, the baton reaches the end with nowhere to land.

With numbers

With k = 5 there are 2 new variables and 3 clauses. Say only l3 is true. Set y1 = 1, y2 = 0: the clauses read (0 ∨ 0 ∨ 1), (0 ∨ 1 ∨ 0), (1 ∨ 0 ∨ 0), all true. With all five literals false, all 4 settings of y1, y2 leave a clause false.

Pass the baton down the chain

Set the clause length k, then switch literals on or off. The device searches every setting of the y variables.

5

Checked by brute force for every k from 4 to 8 and every setting of the literals: the chain is satisfiable exactly when at least one literal is true.

A clause of k literals becomes k − 2 clauses. A short clause gets padding: (l) becomes (l ∨ p ∨ q), (l ∨ p ∨ ¬q), (l ∨ ¬p ∨ q), (l ∨ ¬p ∨ ¬q). All four hold exactly when l is true. CLRS takes a longer route, through the formula's parse tree.

Two literals per clause is easy. 2-SAT is in P: each clause (a ∨ b) becomes ¬a → b and ¬b → a, and strongly connected components (Chapter 22) settle it in linear time.

The failure. Symptom: every formula comes out satisfiable. Measure: test the row where every literal is false. Fix: each link needs ¬yi. Without it, setting every y to 1 satisfies the whole chain.

A clause has 7 literals. How many three-literal clauses and new variables does the chain use?

Chapter 6

3-SAT to Clique: A Formula Becomes a Graph

Build a graph from three clauses, then find the formula's answer as three vertices that all touch

A clique is a set of vertices in which an edge joins every pair. The clique problem asks: does graph G have a clique of k vertices? It is in NP: given k vertices, check the k(k − 1)/2 pairs. To show it is NP-hard, we reduce 3-SAT to it.

Take a formula with m clauses. Here is the one we use, with m = 3:

(x1 ∨ ¬x2 ∨ ¬x3) ∧ (¬x1 ∨ x2 ∨ x3) ∧ (x1 ∨ x2 ∨ x3)

The map f builds a graph in three steps:

  1. Make one vertex for each literal in each clause: 3m = 9 vertices.
  2. Join two vertices when they sit in different clauses and are not a variable and its negation.
  3. Ask for a clique of k = m = 3.

Find the formula in the graph

Switch the variables, and the device picks a true literal in each clause. Or click a vertex to pick it for its clause.

The rule above builds this graph from the formula shown. A brute-force check finds 21 edges, 12 cliques of size 3, and 5 satisfying assignments out of 8.

Of the 27 pairs in different clauses, 6 are a variable against its negation, so the graph has 21 edges. Set x1 = 0, x2 = 0, x3 = 1. Pick ¬x2 from clause 1, ¬x1 from clause 2 and x3 from clause 3. All three pairs are edges: a clique of 3.

Why does it work both ways? A satisfying assignment makes one literal true in each clause. Those m literals sit in different clauses and never clash, so they form a clique. In the other direction, a clique of m has no two vertices in one clause, so it holds exactly one per clause. Its literals never clash, so set them all true and every clause holds.

The graph has 3m vertices and at most 9m(m − 1)/2 edges, so f runs in polynomial time. The counts need not match: 12 cliques against 5 assignments. A clique such as x1, x2, x1 fixes only two variables; any value of x3 completes it.

The failure. Symptom: an unsatisfiable formula maps to a graph with a clique of m. Measure: brute-force both sides on tiny formulas. Fix: keep the "different clauses" rule. With edges inside a clause, three literals of one clause can form the whole clique.

Why does the construction put no edge between two vertices of the same clause?

Chapter 7

The Chain: Clique, Cover, Cycle, Tour

Flip a graph to turn cliques into covers, then price its edges to turn cycles into tours

Hardness travels along reductions. If A ≤P B and B ≤P C, then A ≤P C: run one translation, then the other. A polynomial of a polynomial is a polynomial. CLRS builds this chain:

CIRCUIT-SAT → SAT → 3-CNF-SAT → CLIQUE → VERTEX-COVER → HAM-CYCLE → TSP, and 3-CNF-SAT → SUBSET-SUM

Clique to vertex cover

The complement of a graph G, written G̅, has the same vertices, and an edge exactly where G has none. A clique in G has every inner edge, so in G̅ it has none. Its outside then touches every edge of G̅. Name the number of vertices |V| and the clique size k:

Say it aloud

G has a clique of k vertices if and only if G-bar has a vertex cover of V minus k vertices.

clique of k in G
a clique of k in G k vertices of G, every pair joined.
cover of |V| − k
a cover of V minus k the other |V| − k vertices, which touch every edge.
in G̅
in G-bar in the complement graph: edges where G has none.
In plain words

Build G̅. Ask for a cover of |V| − k. If a clique S exists in G, the vertices outside S cover G̅. If a cover C exists in G̅, the vertices outside C are a clique in G.

With numbers

G below has |V| = 6 and the clique {u, v, x, y}, so k = 4. G̅ has 5 edges, and the outside {w, z} touches all 5. That is a cover of 6 − 4 = 2.

Flip the graph

Click vertices to pick a set S (blue). Switch between G and its complement. In the complement, a pink ring marks the rest of the vertices as a cover.

A made-up graph with 6 vertices and 10 edges. Its largest clique is {u, v, x, y}; the smallest cover of its complement is {w, z}.

Hamiltonian cycle to TSP

The next link, vertex cover to Hamiltonian cycle, uses a small gadget for every edge, 12 vertices in the book's version. The last link is short. Given a graph, make a complete graph on the same vertices. Price an edge of the graph at 0 and a missing edge at 1. Ask: is there a tour of cost at most 0?

GraphCheapest tourHamiltonian cycle?
Square a, b, c, d plus edge a to ca, b, c, d: cost 0Yes
a joined to b, c, d, plus edge b to ccost 1 (d has one edge)No

The failure. Symptom: the cover found is too large, or does not cover. Measure: on a small graph, compare |V| − k with a brute-force cover. Fix: run the cover question on G̅, not on G.

G has 10 vertices and a clique of 6. What vertex cover does that give, and in which graph?

Chapter 8

Subset Sum: When the Numbers Are the Problem

Fill a table of reachable sums, then see why its size depends on the target's value, not its length

You have parcels of 3, 5, 9 and 14 kg. Can you load exactly 17 kg? Subset sum asks: given numbers S and a target T, does some subset of S add up to T? Here 3 + 14 = 17, so yes. For T = 13 the answer is no. CLRS proves subset sum NP-complete from 3-CNF-SAT. Its reduction writes each variable and clause as digits of large numbers.

Yet a short table solves it. Keep a row of the sums you can reach. Start with only 0. For each parcel, add it to every sum already reachable. After the last parcel, look up T.

Fill the table of reachable sums

Each row adds one parcel. A filled cell is a sum you can reach. Drag the target T.

17

Parcels 3, 5, 9 and 14. Reachable sums from 0 to 31: 0, 3, 5, 8, 9, 12, 14, 17, 19, 22, 23, 26, 28, 31.

How much work is that? Name the number of parcels n and the target T. The table has one row per parcel and one cell per sum from 0 to T. Name the bits needed to write T in binary b.

Say it aloud

Work equals n times T plus one, where T is less than two to the b.

work
work the number of table cells the method fills.
n
n the number of parcels: one row each.
T + 1
T plus one one cell for each sum from 0 to T.
T < 2b
T is less than two to the b a number written with b bits can be as large as 2b − 1.
In plain words

Multiply the parcels n by the sums T + 1. That is the work. Now notice that adding one bit to T can double T, so it can double the work.

With numbers

Four parcels and T = 17: 4 × 18 = 72 cells. With b = 64 bits per number, T can reach about 1.8 × 1019, so the table can need about 7.4 × 1019 cells. The whole input is only 5 × 64 = 320 bits.

So the table runs in time polynomial in the value of T but exponential in the length of T. That is pseudo-polynomial time. It does not contradict NP-completeness. It says the hard instances of subset sum are those with huge numbers.

Some NP-complete problems stay hard even when every number is small. They are strongly NP-complete. 3-SAT and clique have no large numbers at all, and TSP stays hard with distances of 1 and 2. For such problems, no pseudo-polynomial algorithm exists unless P = NP.

The failure. Symptom: a packing tool is fast with weights in kilograms and runs out of memory in grams. Measure: watch T, not n: 1,000 times finer units mean 1,000 times more cells. Fix: round the weights to a coarser unit and accept a small error, the idea behind the knapsack approximation schemes of Chapter 35.

The target T gains 10 more bits, and nothing else changes. What happens to the worst-case size of the table?

Chapter 9

Coping: Exact, Approximate, Heuristic

Race an exact search against two fast tour builders and measure what speed costs

The problem is NP-hard and the boss still wants routes on Monday. Proving hardness does not end the work. It tells you which promise to give up: the best answer, speed on every input, or every input.

StrategyGives upExample
Smarter exact searchSpeed on large inputsHeld-Karp: 2n n2 steps instead of (n − 1)!/2 loops
ApproximationThe exact best, within a proven factorVertex cover at most 2 times the smallest
Special casesEvery input2-SAT; vertex cover with small k in about 2k (V + E) steps
HeuristicsAny guaranteeNearest neighbour, then 2-opt

The exact Held-Karp program fills a table of the best path through each subset of places, ending at each place. At n = 20 that is about 4.2 × 108 steps, under a second; at n = 25, about 2.1 × 1010, some 21 seconds. Brute force at n = 20 needs 1.9 years.

A guarantee you can prove

For vertex cover, repeat: take any edge not yet covered, put both its ends in the cover. Name the cover this returns C and the smallest possible cover C*.

Say it aloud

The size of C is at most two times the size of C-star.

|C|
the size of C the vertices in the cover the method returns.
2
two the approximation ratio: the worst the method can do, as a factor.
|C*|
the size of C-star the vertices in a smallest cover, which nobody needs to know.
In plain words

The edges the method takes share no ends. Any cover, C* included, needs one end of each of them. The method takes both ends. So C is at most twice C*.

With numbers

A path a, b, c, d, e, f has 5 edges. The method may take (a, b), (c, d), (e, f): |C| = 6. The smallest cover is {b, d, e}, so |C*| = 3, and 6 ≤ 2 × 3. On a star of one hub and 5 spokes, |C| = 2 and |C*| = 1: the bound is tight.

Race three tour builders

Pick a builder to draw its tour. Change the number of cities or scatter new ones. The read-out compares all three lengths.

8

Illustrative random cities. Exact search tries every loop, (n − 1)!/2 of them. Nearest neighbour starts at city 0 and always goes to the closest unvisited city. 2-opt then reverses any stretch of the tour that shortens it, until none does.

Nearest neighbour is fast and often a little long. 2-opt repairs most crossings. Exact search wins, but each new city multiplies its work by about n. With distances that obey the triangle inequality, Christofides' method guarantees at most 3/2 times the best. Without it, no constant factor is possible unless P = NP. Chapter 35 proves both bounds.

The failure. Symptom: a heuristic tour is 20% too long on some inputs, and nobody notices. Measure: on small inputs, compare with the exact answer; on large ones, with a lower bound. Fix: report the gap, and use a method with a proven ratio when the gap matters.

Which method is guaranteed to return the shortest tour?

Chapter 10

Field Guide

Keep the terms, the numbers, the proof recipe and the code in one place

A problem is in NP when a yes answer has a short certificate with a fast check. It is NP-complete when it is in NP and every NP problem reduces to it. Cook and Levin found the first; every later proof reduces a known NP-complete problem to the new one. Whether P equals NP is open.

Proven, and believed

StatementStatus
P ⊆ NPProven: a solver is a verifier that ignores the certificate.
SAT and circuit satisfiability are NP-completeProven (Cook 1971, Levin 1973).
One NP-complete problem in P gives P = NPProven, from the definition.
2-SAT, 2-colouring and primality are in PProven.
P ≠ NPBelieved by most researchers, not proven. A Clay Millennium Prize problem since 2000.
NP ≠ co-NPBelieved, not proven. It would imply P ≠ NP.
If P ≠ NP, some NP problems are neither in P nor NP-completeProven (Ladner, 1975). Factoring and graph isomorphism are candidates.

The numbers that matter

WhatNumber
Loops through n places(n − 1)!/2: 12 at n = 5; 4.4 × 1010 at 15; 6.1 × 1016 at 20
Held-Karp steps2n n2: 4.2 × 108 at n = 20; 2.1 × 1010 at 25
Yes or no questions for a range of 1017
Checking a Hamiltonian cycle on 8 vertices16 checks, against 2,520 loops
Long clause of k literals in 3-CNFk − 2 clauses, k − 3 new variables
3-SAT to clique, m clauses3m vertices, clique of m
Clique of k, |V| verticesCover of |V| − k in the complement
Subset sum tablen (T + 1) cells; exponential in the bits of T
Vertex cover by both ends of an edgeAt most 2 times the smallest

The terms, one line each

TermMeaning
Decision problemA question with a yes or no answer for each instance.
PDecision problems solved in time polynomial in the input length.
CertificateShort evidence that the answer is yes.
NPDecision problems whose yes answers have certificates a polynomial-time verifier accepts.
Reduction A ≤P BA polynomial-time f with x in A exactly when f(x) is in B.
NP-hardEvery NP problem reduces to it.
NP-completeNP-hard and in NP.
Pseudo-polynomialPolynomial in the values of the numbers, not in their length.

The proof recipe

  1. Show the new problem X is in NP: name the certificate and a polynomial-time check.
  2. Pick a known NP-complete problem K whose shape is close to X.
  3. Write the map f from instances of K to instances of X.
  4. Prove a yes for K gives a yes for X.
  5. Prove a yes for X gives a yes for K.
  6. Show f runs in polynomial time.

The core as code

pythonfrom itertools import combinations, product

def verify_ham_cycle(n, edges, cycle):          # the verifier A(x, y): 2n checks
    E = {frozenset(e) for e in edges}
    if sorted(cycle) != list(range(n)): return False   # each vertex exactly once
    return all(frozenset((cycle[i], cycle[(i + 1) % n])) in E for i in range(n))

def sat3_to_clique(clauses):                     # the map f: formula -> (graph, k)
    V = [(r, lit) for r, c in enumerate(clauses) for lit in c]   # literal +i means x_i, -i means not x_i
    E = [(a, b) for a, b in combinations(range(len(V)), 2)
         if V[a][0] != V[b][0] and V[a][1] != -V[b][1]]
    return V, E, len(clauses)

def has_clique(n_vertices, E, k):                # brute force: fine for 9 vertices
    E = set(E)
    return any(all((a, b) in E for a, b in combinations(S, 2))
               for S in combinations(range(n_vertices), k))

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

phi = [[1, -2, -3], [-1, 2, 3], [1, 2, 3]]
V, E, k = sat3_to_clique(phi)
print(len(V), len(E), k)                                    # 9 21 3
print(satisfiable(phi, 3), has_clique(len(V), E, k))         # True True: the answers match

def subset_sum(nums, T):                         # pseudo-polynomial: n * (T + 1) cells
    reach = [True] + [False] * T
    for x in nums:
        for s in range(T, x - 1, -1):               # downward, so each parcel is used once
            reach[s] = reach[s] or reach[s - x]
    return reach[T]

print(subset_sum([3, 5, 9, 14], 17), subset_sum([3, 5, 9, 14], 13))   # True False

Keep going

The takeaway. Checking can be fast when finding is not known to be. Reductions carry hardness from SAT to clique, cover, cycle, tour and subset sum. When your problem joins that family, choose what to give up: the exact best, speed, or generality.
To prove a new problem X is NP-complete, which two things must you show?

Now press Present or Teach and explain from memory: what a certificate is, how a reduction moves hardness, and the chain from circuits to tours. Then go back to the hero and say why the checker's bar never grows like the searcher's grid.

Credit and source

This lesson re-teaches Chapter 34 of Introduction to Algorithms, third edition, by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein (MIT Press, 2009). The chain of reductions follows the book. The example graphs, formulas and devices are our own.

NP-Completeness (CLRS Chapter 34)
Next: Approximation Algorithms · Back to Gleams