Some problems have no known fast exact method. An approximation algorithm runs fast and proves a limit: its answer is never worse than ρ times the best one. For vertex cover, ρ is 2.
Pick an algorithm and press Run 20. Each dot is one random problem, solved fast and also by brute force. No dot crosses its green line. Then we build each algorithm and its proof from zero.
You need a little Python, the idea of a graph, and what NP-hard means. We build the rest from zero.
Based on Chapter 35, Approximation Algorithms, of Introduction to Algorithms (CLRS) by Cormen, Leiserson, Rivest and Stein. Previous: NP-Completeness.
Illustrative random problems, small enough for brute force: 8-vertex graphs, 7 cities, 10 elements in 8 sets of at most 4, and 10 clauses on 5 variables. Ratio = fast answer / best for a minimum, best / fast answer for a maximum. MAX-3-CNF's line holds on average; the teal diamond is that average.
Chapter 0
Trade the exact answer for a fast one that carries a proven limit
You drive a van to 15 stops and want the shortest round trip. This is the travelling salesman problem (TSP). Chapter 34 shows that it is NP-hard: no one knows a polynomial-time exact method, and most experts believe none exists.
Brute force tries every tour. Count them before you start.
Drag the size. The bar is the count of candidates on a log scale. The ticks mark run times at a billion checks a second.
Counts are exact: (n − 1)!/2 tours through n cities, 2n subsets of n vertices. The billion-a-second machine is illustrative.
Fifteen stops take seconds. Thirty take longer than the age of the universe. So we give up the exact answer and ask for a fast answer with a proven limit.
An approximation algorithm runs in polynomial time and proves how far its answer can be from the best one. Call the cost of its answer C and the cost of the best answer C*, said "C-star". For an input of n items, the promised limit is a number ρ(n), said "rho of n".
The larger of C over C-star and C-star over C is at most rho of n.
For a minimum problem, divide your cost C by the best cost C*. For a maximum problem, divide C* by your value C. A ρ(n)-approximation keeps that quotient at or under ρ(n) on every input.
Chapter 1's algorithm can return 6 cameras where the best needs 3: C / C* = 6 / 3 = 2, right on its limit ρ = 2. Chapter 2's tour of 21.52 km against the best 16.15 km gives 1.33, under its limit of 2.
There is a catch: you never know C*. Computing it is the hard problem. Every proof in this lesson uses the lower-bound method: find a number L that you can compute and that is at most C*. Then show C ≤ ρ · L. Since L ≤ C*, you get C ≤ ρ · C*.
| Problem | Lower bound L ≤ C* | Ratio |
|---|---|---|
| Vertex cover | the number of edges in a matching | 2 |
| Metric TSP | the weight of a minimum spanning tree | 2 |
| Weighted vertex cover | the value of a linear program | 2 |
| MAX-3-CNF (a maximum) | the clause count m is an upper bound on C* | 8/7, on average |
The failure. Symptom: a heuristic looks good on your tests, then returns a bad answer on one input. Measure: on inputs small enough for brute force, compute C / C*; one quotient above your claim disproves it. Fix: claim only a ratio you can prove.
Chapter 1
Pick an untouched edge, keep both of its vertices, and prove the factor 2
A building has seven rooms, A to G, and eight hallways. A camera in a room watches every hallway that touches that room. You want every hallway watched with as few cameras as possible.
In graph words, a vertex cover is a set of vertices that touches every edge. Finding the smallest one is NP-complete (Chapter 34). CLRS gives this algorithm, APPROX-VERTEX-COVER:
Tap an untouched edge, on the graph or as a chip. Its two rooms join the cover. Try to finish with a small cover, then show the best.
Illustrative graph of our own. Warm edges are the picked edges; grey edges are already touched. Brute force over all 128 subsets finds one smallest cover, {B, D, F}.
The picked edges never share a vertex, because each pick needs an edge that no chosen vertex touches. Edges that share no vertex form a matching. Call the set of picked edges A, the algorithm's cover C, and a smallest cover C*.
The size of C equals two times the size of A, which is at most two times the size of C-star.
Each picked edge in A adds two new vertices, so C has 2|A| vertices. Any cover, the best one too, must touch every edge in A. No two of those edges share a vertex, so C* needs a different vertex for each: |C*| ≥ |A|.
In list order the algorithm picks A-B, C-D and E-F: |A| = 3 and |C| = 6. The best cover is {B, D, F}, so |C*| = 3. Then 6 = 2 × 3 ≤ 2 × 3: the bound is met exactly. Another order picks B-D and E-F: 4 vertices, a quotient of 4/3.
The bound is tight. On a graph of separate edges, each edge forces both its ends into C, but the best cover needs one end per edge. On a star, one center and many leaves, the algorithm takes the center and one leaf: 2 cameras where 1 is enough.
The failure. Symptom: you "improve" the rule by picking the busiest room first. Measure: CLRS Exercise 35.1-3 shows that this rule misses ratio 2. On some graphs its quotient grows like log n. Fix: keep the matching rule when you need a guarantee.
Chapter 2
Build a minimum spanning tree, walk it in preorder, and skip cities you have seen
Seven cities, A to G, lie on a map. The salesman must visit each city once and come home. Distances are straight lines, so a direct trip is never longer than a detour. That rule is the triangle inequality: for any cities u, v and w, d(u, w) ≤ d(u, v) + d(v, w). TSP with this rule is metric TSP.
CLRS gives APPROX-TSP-TOUR:
Drag any city. The tree, the walk H and the best tour update at once. Turn the layers on and off.
Illustrative map in km. Prim builds T from A; preorder visits children in letter order. The best tour comes from brute force over all 360 tours.
Why is H at most twice the best? Call the total length of a set of edges c(·), the tree T, our tour H, and the best tour H*.
c of T is at most c of H-star, which is at most c of H, which is at most two c of T.
Delete one leg of the best tour H*. What stays is a path through every city, which is a spanning tree, so c(T) ≤ c(H*). A full walk around T crosses each tree edge twice: 2 c(T). Our tour H skips cities seen before, and by the triangle inequality each skip is no longer than the path it replaces.
On our seven cities: c(T) = 12.84 km, c(H*) = 16.15 km, c(H) = 21.52 km and 2 c(T) = 25.69 km. So 12.84 ≤ 16.15 ≤ 21.52 ≤ 25.69. Our quotient is 21.52 / 16.15 = 1.33.
Christofides (1976) does better: he adds a cheapest matching on the tree's odd-degree cities in place of doubling the tree, and gets ratio 3/2. Karlin, Klein and Oveis Gharan (2021) pushed the ratio below 3/2, by about 10−36.
The failure. Symptom: a tour comes out longer than 2 c(T). Measure: test d(u, w) ≤ d(u, v) + d(v, w) on every triple of cities. Fix: if the salesman may pass through a city twice, replace each distance by the shortest-path distance, which always obeys the rule.
Chapter 3
Watch the shortcut break, then prove that general TSP has no ratio at all
Prices often break the triangle inequality: a direct flight can cost more than two flights through a hub. Take four cities. A is 1 from each of B, C and D; C-D and B-D cost 2; you set the price d of B-C. The tree is the star at A, and the walk is A, B, C, D, A.
Drag the price of B-C. While it is 2 or less, the triangle inequality holds. Watch the walk against its limit 2 c(T) = 6.
Illustrative prices. The walk costs 1 + d + 2 + 1. The best tour, A-B-D-C-A, costs 6 and avoids B-C.
The walk costs d + 4. It passes the limit 6 exactly when d passes 2, the point where B-C costs more than B-A-C.
No other algorithm fixes this. CLRS Theorem 35.3: if P ≠ NP, then for every constant ρ ≥ 1, no polynomial-time algorithm has ratio ρ for general TSP. The proof turns such an algorithm into a solver for Hamiltonian cycle: does a graph G have a loop through every vertex once? That question is NP-complete (Chapter 34).
Take G with vertex set V and edge set E. On the same vertices, give every pair a price w(u, v): cheap for an edge of G, dear for a non-edge.
w of u v equals one if u v is an edge of G, and rho times the size of V plus one otherwise.
If G has a Hamiltonian cycle, the best tour costs n, so a ρ-approximation returns at most ρn. If G has none, every tour uses a dear pair and costs more than ρn. The answer tells you which case holds.
Take n = 5 and ρ = 2: a non-edge costs 2 × 5 + 1 = 11. With a Hamiltonian cycle, the best tour costs 5, so the algorithm returns at most 10. Without one, every tour costs at least 4 + 11 = 15. Under 10 means yes; 15 or more means no.
Choose a graph and a ratio ρ. Solid edges cost 1; every missing edge costs ρn + 1. The ruler shows where the algorithm's answer must land in each case.
The bowtie is two triangles that share vertex A, so any loop through every vertex must pass A twice: no Hamiltonian cycle. Best tours come from brute force over all 12 tours.
The failure. Symptom: on fares or latencies, the tree walk returns a tour many times too long. Measure: count the triples that break the triangle inequality. Fix: if the salesman may revisit cities, use shortest-path distances. If not, no ratio is possible unless P = NP: use an exact solver on small inputs.
Chapter 4
Take the set that covers the most new elements, and pay at most a harmonic factor
You place radio masts. Each possible site reaches a set of towns. You want every town reached with as few masts as possible.
That is set cover. Given a universe X of n elements and a family F of subsets of X, find the fewest sets from F whose union is X. CLRS's GREEDY-SET-COVER repeats one step: take the set that covers the most elements not yet covered.
Two rows of towns. Each row alone is a set, and the two rows are the best cover. The column blocks are bigger, so greedy takes them. Press Next, then grow the trap.
Illustrative family: each row has 2k − 1 towns; block j holds 2k−j towns, half from each row. Each block covers one more new town than a row, so greedy never takes a row.
Greedy pays k sets where 2 suffice, and k grows like log n. How bad can it get? Call greedy's cover C and a smallest cover C*. Call the size of the largest set in F d. The harmonic number is H(d) = 1 + 1/2 + … + 1/d.
The size of C is at most H of d times the size of C-star.
Each time greedy takes a set that covers k new elements, charge each of them 1/k. The charges add up to |C|. Inside one set S of the best cover, the last element to be covered pays at most 1, the one before at most 1/2, and so on. That is at most H(d) per set; add over the |C*| sets.
With k = 3 blocks: n = 14 towns and d = 8, so H(8) = 2.72. The best cover has |C*| = 2 sets, so the bound allows 2.72 × 2 = 5.44 sets. Greedy takes 3. With k = 6: n = 126, greedy takes 6, the bound allows 9.49.
Why at most 1/j? When S still has j uncovered elements, S itself could cover j of them. Greedy takes a set that covers at least as many, so each new element pays at most 1/j.
The failure. Symptom: greedy takes more sets than you expected. Measure: on small inputs, find C* by brute force. Fix: on large inputs, accept it. Unless P = NP, no polynomial-time algorithm reaches (1 − ε) ln n (Dinur and Steurer, 2014).
Chapter 5
Set every variable at random and satisfy seven clauses in eight, on average
A literal is a variable or its negation, such as x or ¬x. A clause joins literals with OR. A 3-CNF formula joins clauses with AND, and each clause has exactly three literals on three different variables. MAX-3-CNF asks for true or false values that satisfy as many clauses as possible.
CLRS's algorithm uses no thought at all: set each variable true with probability 1/2, on its own coin.
Each row is a clause; it lights when one of its literals is true. Flip once, then flip 100 times and watch the average settle.
Illustrative formulas. A has 8 clauses on 4 variables and can satisfy all 8. B holds all 8 sign patterns on x, y, z, so every assignment satisfies exactly 7. Best values come from all 2n assignments.
Why seven in eight? A clause is false only when all three of its literals are false. Call the number of clauses m and the number of satisfied clauses Y. Y depends on the coins, so we ask for its expected value E[Y]: the average over many runs.
E of Y equals the sum over i of the probability that clause i is true, which equals m times seven eighths.
Each literal is false with probability 1/2, and the three coins are separate, so a clause fails with probability 1/8. Add 7/8 once for each of the m clauses. The best possible count is at most m, so best / E[Y] ≤ m / (7m/8) = 8/7.
Formula A has m = 8, so E[Y] = 8 × 7/8 = 7. Over its 16 assignments, 4 satisfy 6 clauses, 8 satisfy 7 and 4 satisfy 8: the average is 7. The best is 8, and 8 / 7 = 1.14.
CLRS calls this a randomized 8/7-approximation: the ratio holds for the expected value. Formula B shows the method cannot do better on every formula: no assignment beats 7 of its 8 clauses.
The failure. Symptom: one run satisfies only 6 of formula A's 8 clauses, a quotient of 1.33. Measure: the bound is on the average, so repeat runs and track the mean. Fix: keep the best of several runs. Or remove the coins with the method of conditional expectations: fix the variables one at a time. Give each the value that leaves the larger expected count over the coins still to flip.
Chapter 6
Solve a linear program with fractions, keep every vertex at one half or more
Now each room has a price for its camera, its weight w(v). Chapter 1's rule ignores prices: it could buy a camera for 4 where one for 1 would do. We need a lower bound that knows the prices.
Write the problem with a number x(v) per vertex: 1 means "buy", 0 means "skip". Each edge (u, v) needs x(u) + x(v) ≥ 1. Minimise Σ w(v) x(v). With x(v) in {0, 1} this is still NP-hard. Now relax it: allow any x(v) from 0 to 1. The result is a linear program (LP), which polynomial-time methods solve. Call its best value z*.
CLRS's APPROX-MIN-WEIGHT-VC solves the LP, then rounds: buy a camera in every room with x(v) ≥ 1/2.
Tap a room to change its price from 1 to 4. The fill shows its LP value x(v). A warm ring means rounding buys it; a blue ring marks the best cover.
Illustrative prices. This LP always has a best solution with every x(v) equal to 0, 1/2 or 1 (Nemhauser and Trotter, 1975). The device searches those 729 choices.
Call the rounded cover C and the cheapest cover C*. Write w(·) for the total price of a set of rooms.
w of C is at most two z-star, which is at most two w of C-star.
Each edge has x(u) + x(v) ≥ 1, so one end has at least 1/2 and C touches every edge. Each room in C has x(v) ≥ 1/2, so w(v) ≤ 2 w(v) x(v). Add over C: w(C) ≤ 2 z*. The real cover C* is one of the LP's allowed answers, so z* ≤ w(C*).
Prices A 4, B 4, C 1, D 1, E 4, F 1. The LP gives A, B and C one half each, D and F 1, and E 0: z* = 2 + 2 + 0.5 + 1 + 1 = 6.5. Rounding buys A, B, C, D and F: w(C) = 11. The cheapest cover, {A, C, D, F}, costs 7. So 6.5 ≤ 7 ≤ 11 ≤ 13.
The failure. Symptom: rounding pays almost double. Measure: compare w(C) with z*; the quotient w(C*) / z* is the LP's integrality gap. Fix: none inside this LP. On a triangle with unit prices, z* = 1.5 but the best cover costs 2. On the complete graph with n vertices, z* = n/2 and the best costs n − 1, so the gap tends to 2.
Chapter 7
Drop sums that sit close to a kept sum, and choose your own accuracy ε
A truck carries t = 308 kg. Crates weigh 104, 102, 201 and 101 kg. Which crates fill it best without going over? That is subset sum: find the largest subset total that is at most t.
The exact method keeps a sorted list of every reachable total. For each new number x, it merges the list with a copy that has x added, then drops totals above t. The list can double at each step: here it grows 2, 4, 7, 12. The best total is 307 = 104 + 102 + 101.
CLRS's APPROX-SUBSET-SUM trims each list with a small width δ, said "delta". It drops a total y when a kept total z sits just below it.
y over one plus delta is at most z, which is at most y.
Walk up the sorted list. Keep a total only if it is more than 1 + δ times the last total you kept. Every dropped y then has a stand-in z that is smaller by at most a factor 1 + δ.
With ε = 0.40 and n = 4, δ = 0.40 / 8 = 0.05. After the second crate the list is 0, 102, 104, 206. Since 104 / 1.05 = 99.05 ≤ 102 ≤ 104, the total 102 stands in for 104 and 104 goes.
Each pair of bars is one step: grey is the exact list length, warm is the trimmed one. Drag ε and read the answer against the best.
Four crates: the worked example of CLRS Section 35.5, t = 308. Twelve crates: our own random weights from 100 to 999 kg, t = 2,695. Bars use a square-root scale.
Call the best total y* and the returned total z*.
y-star over z-star is at most one plus epsilon over two n, to the n, which is at most one plus epsilon.
Follow the best subset through the n steps. Each trim may swap its running total for a stand-in up to 1 + ε/2n times smaller. After n trims the loss is at most (1 + ε/2n)n, below 1 + ε when ε ≤ 1.
The lists become 0, 104; then 0, 102, 206; then 0, 102, 201, 303; then 0, 101, 201, 302. So z* = 302 and y* = 307: 307 / 302 = 1.017. The bound allows (1.05)4 = 1.22, under 1 + 0.40 = 1.40.
Kept totals grow by a factor above 1 + δ each, so a list holds at most (3n ln t) / ε + 2 of them. The time is polynomial in n, in the digits of t, and in 1/ε: a fully polynomial-time approximation scheme (FPTAS). A plain PTAS may take time like n1/ε.
The failure. Symptom: you trim with δ = ε and miss by more than 1 + ε. Measure: the loss can reach (1 + ε)n, which is 3.84 for ε = 0.40 and n = 4. Fix: δ = ε/2n.
Chapter 8
Separate what is proven from what holds only if a conjecture is true
An algorithm's ratio is a theorem with no assumption: vertex cover has a 2-approximation. A hardness result says no polynomial-time algorithm does better unless P = NP. It depends on P ≠ NP, which nobody has proved.
Some limits need more: the Unique Games Conjecture (UGC), stated by Subhash Khot in 2002 and still open. Most hardness results trace back to the PCP theorem. It says a checker can test a proof of any NP statement with O(log n) random bits and a constant number of reads.
Each row is a ratio scale from 1. Green: a proven algorithm reaches it. Red: ruled out unless P = NP. Pink: ruled out if the UGC holds. Grey: open.
Log scale from 1 to 16. Every limit is for polynomial-time algorithms and for every fixed ε > 0. Sources are named in the read-out and in the field guide.
| Problem | Proven algorithm | No better unless P = NP | No better if the UGC holds |
|---|---|---|---|
| Subset sum | 1 + ε, any ε (FPTAS) | nothing left to rule out | — |
| MAX-3-CNF | 8/7, on average | 8/7 − ε (Håstad, 2001) | — |
| Metric TSP | 2; 3/2 (Christofides); just under 3/2 | 123/122 ≈ 1.008 | — |
| Vertex cover | 2 | √2 − ε ≈ 1.41 | 2 − ε |
| Set cover | H(d) ≤ ln n + 1 | (1 − ε) ln n | — |
| General TSP | none | no constant at all | — |
Given P ≠ NP, the coin flip and greedy are best possible, up to ε. Metric TSP has an open gap from 1.008 to just under 1.5. Vertex cover closes at 2 only if the UGC holds.
The failure. Symptom: a report says "vertex cover cannot beat 2". Measure: find the condition behind the claim. Fix: write "no 2 − ε ratio if the UGC holds; no √2 − ε ratio unless P = NP".
Chapter 9
Keep the terms, the numbers, the checks and the core code on one page
An approximation algorithm trades the exact answer for polynomial time and a proven ratio ρ. Each proof compares the answer with a bound you can compute: a matching, a spanning tree, an LP value, or the clause count. Hardness results say where the trade stops, and each one names its assumption.
| Term | Meaning | Number on this page |
|---|---|---|
| Ratio ρ(n) | max(C/C*, C*/C) on every input of size n | 150 / 100 = 1.5 |
| Vertex cover | both ends of a maximal matching; |C| = 2|A| ≤ 2|C*| | 6 against {B, D, F}, ratio 2 |
| Metric TSP | MST preorder walk; c(T) ≤ c(H*) ≤ c(H) ≤ 2c(T) | 12.84 ≤ 16.15 ≤ 21.52 ≤ 25.69 |
| General TSP | no constant ratio unless P = NP | non-edge price ρn + 1 = 11 |
| Set cover | greedy; |C| ≤ H(d)|C*| | 3 sets against 2, bound 5.44 |
| MAX-3-CNF | random coins; E[Y] = 7m/8 | 7 of 8 on average, best 8 |
| Weighted vertex cover | LP, keep x(v) ≥ 1/2; w(C) ≤ 2z* ≤ 2w(C*) | 6.5 ≤ 7 ≤ 11 ≤ 13 |
| Subset sum FPTAS | trim with δ = ε/2n; y*/z* ≤ 1 + ε | 302 against 307 |
def approx_vertex_cover(edges): cover = set() for u, v in edges: # any order works if u not in cover and v not in cover: cover |= {u, v} # take BOTH ends return cover # |cover| <= 2 * OPT def approx_tsp_tour(parent): # parent[v] from Prim, root 0 kids = {v: [] for v in range(len(parent))} for v, p in enumerate(parent): if p >= 0: kids[p].append(v) tour, stack = [], [0] while stack: # preorder walk u = stack.pop(); tour.append(u) stack.extend(reversed(kids[u])) return tour + [0] # needs the triangle inequality def greedy_set_cover(X, F): left, chosen = set(X), [] while left: S = max(F, key=lambda s: len(s & left)) chosen.append(S); left -= S return chosen # <= H(max |S|) * OPT def approx_subset_sum(S, t, eps): delta, L = eps / (2 * len(S)), [0] for x in S: L = sorted(set(L) | {y + x for y in L}) kept = [L[0]] for y in L[1:]: if y > kept[-1] * (1 + delta): kept.append(y) L = [y for y in kept if y <= t] return max(L) # [104,102,201,101], 308, 0.4 -> 302
This chapter needs NP-completeness to say why exact answers are out of reach, and its reductions to prove the limits. It reuses the minimum spanning tree for the TSP walk and the greedy idea of Chapter 16 for set cover. Rounding needs linear programming, and subset sum builds on dynamic programming.
Now press Present or Teach. Prove |C| = 2|A| ≤ 2|C*| from memory, then run the four-crate trim to 302. Then go back to the hero, run MAX-3-CNF, and say why one of its dots may cross the line while the diamond never does.
T. H. Cormen, C. E. Leiserson, R. L. Rivest and C. Stein, Introduction to Algorithms, MIT Press, Chapter 35, Approximation Algorithms (third edition numbering); the four-crate subset-sum example is theirs. Other results named: N. Christofides (1976); A. Karlin, N. Klein and S. Oveis Gharan (2021); G. Nemhauser and L. Trotter (1975); J. Håstad (2001); I. Dinur and D. Steurer (2014); S. Khot (2002); S. Khot and O. Regev (2008); S. Khot, D. Minzer and M. Safra (2018); M. Karpinski, M. Lampis and R. Schmied (2015). The graphs, maps, formulas, prices and devices on this page are our own.