Coping with NP-Hardness
Parameterized and exact algorithms, SAT solvers, and the fine-grained limits of polynomial time.
"NP-hard" is a statement about the worst case over all inputs as they grow without bound. Your input is one instance, with a size, a structure and often a small hidden parameter. Every method that solves NP-hard problems in practice exploits one of those three, and this lesson is a map of them.
What you’ll learn
- Choose an exact exponential algorithm from the input size: permutations (), DP over subsets (), meet in the middle (), and pruned search beyond.
- Prove that vertex cover can be solved in time by a bounded search tree, and shrink instances to edges with Buss's kernel.
- Exploit special structure (trees, bipartite graphs, DAGs, bounded treewidth), and hand an NP-hard core to a SAT or integer-programming solver through an encoding.
- Use local search such as 2-opt and simulated annealing, knowing what it does and does not guarantee.
- State what SETH, the 3SUM conjecture and the APSP conjecture predict about problems that are already polynomial.
Beat brute force, exactly
When the input is small, an exact algorithm is the answer, but some exponentials are vastly smaller than others. For the traveling salesman problem, brute force checks tours, while the Held–Karp dynamic program over subsets fills table entries, in time. Read the constraints with this course's rule of thumb, about simple operations per second (a rule of thumb, not a law):
| Input size | Exact method that fits | Example |
|---|---|---|
| – | all permutations, | brute-force TSP on 10 cities: 181,440 tours |
| – | DP over subsets, to | Held–Karp: TSP on 20 cities in under a second |
| meet in the middle, | subset sum on 40 numbers: two lists of half-sums (Horowitz & Sahni, 1974) | |
| larger | branch and bound: prune by feasibility and by bounds | knapsack and TSP solvers that prune with LP bounds |
Brute force checks tours. For 20 cities, at tours per second, how long does it take?
- About a second
- About an hour
- About 19 years
- Longer than the age of the universe
Show the answer
C. About 19 years
tours take about seconds: 19 years. Held–Karp compares about sums for the same 20 cities, under half a second.
Beyond the sizes where a clean exponential fits, exact search survives through pruning: discard every branch that cannot contain a solution, or, in branch and bound, that cannot beat the best solution found so far. The worst case stays exponential, but on typical inputs the savings are enormous.
Fixed-parameter tractability: when k is small
Many instances are huge but have a small parameter: a vertex cover of size in a graph with a million edges. Trying all candidate covers is hopeless. A fixed-parameter tractable algorithm runs in time, with all the exponential growth in . The simplest technique is a bounded search tree: every edge forces or into the cover, so branch on the two.
def vc_search(edges, k):
"""A vertex cover of size <= k as a set, or None if there is none."""
if not edges:
return set()
if k == 0:
return None
u, v = edges[0] # u or v must be in every cover
for w in (u, v):
rest = [e for e in edges if w not in e]
sub = vc_search(rest, k - 1)
if sub is not None:
return sub | {w}
return NoneEach call deletes the edges of the chosen vertex in time and lowers by one. Tested against brute force on 1,500 random graphs.
Correct, by induction on . Every vertex cover contains or . If a cover with contains , then covers every edge that avoids , so the recursive call for , with budget , succeeds. Conversely, anything returned is a cover of size at most .
Bounded. Each call makes at most two recursive calls and lowers , so the recursion tree is binary with depth at most :
Time. Each call filters the edge list once:
Kernelization shrinks the instance before any branching. Buss's rule (Buss & Goldsmith, 1993): a vertex of degree more than belongs to every cover of size at most , because a cover without it would need all its more than neighbors. Take it, lower , and repeat. Afterwards every degree is at most , so vertices cover at most edges: if more remain, the answer is no; otherwise at most edges are left, however large the original graph.
def buss_kernel(edges, k):
"""(forced vertices, remaining edges, new k), or None if no cover of size <= k exists."""
forced = set()
while True:
deg = {}
for u, v in edges:
deg[u] = deg.get(u, 0) + 1
deg[v] = deg.get(v, 0) + 1
high = [w for w, d in deg.items() if d > k]
if not high:
break
w = high[0] # degree > k: w is in every small cover
forced.add(w)
edges = [e for e in edges if w not in e]
k -= 1
if k < 0:
return None
if len(edges) > k * k: # k vertices of degree <= k cover <= k^2 edges
return None
return forced, edges, k
star_and_triangle = [(0, i) for i in range(1, 26)] + [(30, 31), (31, 32), (30, 32)]
print(buss_kernel(star_and_triangle, 3)) # ({0}, [(30, 31), (31, 32), (30, 32)], 2)On a star with 25 leaves plus a separate triangle, with : the center, of degree 25, is forced, and what remains is a triangle with budget 2. Checked against brute force: the kernel has a cover within its budget exactly when the original graph does.
After Buss's rule with , at most how many edges can a yes-instance have left?
Show the answer
400
Every remaining degree is at most , so 20 cover vertices touch at most edges. The search tree then runs on at most 400 edges, whatever the original size: time in all.
Smarter branching lowers the base of the exponential: branch on a vertex of degree at least 3, putting either or all of its neighbors into the cover. The best published bounds are (Chen, Kanj & Xia, 2010) and about (Harris & Narayanaswamy, 2024). The Optimal lesson Parameterized Algorithms & Kernelization derives such bounds, and explains why -clique, solvable in time, is believed to have no algorithm of this kind.
Special structure
NP-hardness is proved on the hardest graphs. Real inputs are often trees, bipartite graphs, DAGs, grids, interval schedules, or graphs that are nearly trees, and on such classes many hard problems become polynomial:
| Problem | In general | Polynomial when | How |
|---|---|---|---|
| Maximum independent set, minimum vertex cover | NP-hard | the graph is a tree | tree DP: each vertex in or out, |
| Minimum vertex cover | NP-hard | the graph is bipartite | König's theorem: it equals a maximum matching, found with a flow algorithm |
| Graph coloring | NP-hard for 3 colors | the graph is an interval graph | greedy coloring by left endpoint is optimal |
| Longest path | NP-hard | the graph is a DAG | dynamic programming in topological order |
| Satisfiability | NP-complete for 3-CNF | every clause has 2 literals | 2-SAT through strongly connected components, |
| Independent set, coloring, Hamiltonian cycle, … | NP-hard | the treewidth is at most | DP over a tree decomposition in time (Courcelle's theorem) |
Which of these special cases is still NP-complete?
- Vertex cover in a bipartite graph
- Maximum independent set in a tree
- Satisfiability of a 2-CNF formula
- 3-coloring a planar graph
Show the answer
D. 3-coloring a planar graph
Deciding whether a planar graph is 3-colorable is NP-complete (Garey, Johnson & Stockmeyer, 1976), even though every planar graph is 4-colorable, so the analogous question for 4 colors always has the answer yes.
So before reaching for heavy machinery, ask what your inputs really are. A "graph" from a file system is a tree; a dependency graph is a DAG; a timetable of lectures is an interval graph; a road network is nearly planar with small separators. The Optimal lesson Parameterized Algorithms & Kernelization shows how treewidth turns "nearly a tree" into running times.
Solvers and local search
When the instance is large and has no exploitable structure, the strongest tools are general-purpose solvers: SAT solvers for Boolean constraints, mixed-integer programming (MIP) solvers for linear models with integer variables, and constraint-programming solvers for scheduling. You encode the problem and let decades of engineering do the search. Graph 3-coloring becomes a CNF formula in a few lines:
def coloring_cnf(n, edges, colors=3):
var = lambda v, c: v * colors + c + 1 # variables 1, 2, ... as in DIMACS
cnf = []
for v in range(n):
cnf.append([var(v, c) for c in range(colors)]) # v gets some color
cnf += [[-var(v, a), -var(v, b)] # ... and at most one
for a in range(colors) for b in range(a + 1, colors)]
for u, v in edges:
cnf += [[-var(u, c), -var(v, c)] for c in range(colors)] # endpoints differ
return cnf
petersen = ([(i, (i + 1) % 5) for i in range(5)] + [(i, i + 5) for i in range(5)]
+ [(5 + i, 5 + (i + 2) % 5) for i in range(5)])
print(len(coloring_cnf(10, petersen))) # 85 clauses over 30 variablesOne variable per (vertex, color) pair: "some color" clauses, "at most one" clauses and conflict clauses. The Petersen graph gives 85 clauses over 30 variables; the formula for is unsatisfiable, as brute force over its assignments confirms. Industrial solvers decide formulas with millions of variables, although their worst case stays exponential (SAT Solvers in Practice).
Local search starts from any solution and applies improving moves until none is left. For TSP the classic move is 2-opt: remove two edges and reconnect the two paths the other way. The result is a local optimum, which need not be the optimum, and 2-opt comes with no constant worst-case guarantee. Simulated annealing (Kirkpatrick, Gelatt & Vecchi, 1983) also accepts worsening moves, with a probability that shrinks over time, to escape local optima; tabu search, random restarts and genetic algorithms are other escapes. Exact algorithms prove; heuristics only find.
The fine-grained limits of polynomial time
Hardness does not stop at NP. Several problems have simple polynomial algorithms that nobody has beaten by a polynomial factor in decades: edit distance in , 3SUM in , all-pairs shortest paths in . Fine-grained complexity explains this the way NP-completeness explains exponential time: through reductions from a few problems conjectured to be hard.
| Conjecture (unproven) | Statement | What it rules out |
|---|---|---|
| SETH (Impagliazzo & Paturi, 2001) | for every there is a such that -SAT on variables needs more than time | edit distance and longest common subsequence in (Backurs & Indyk, 2015; Abboud, Backurs & Vassilevska Williams, 2015) |
| 3SUM conjecture | deciding whether integers contain needs time | algorithms for collinearity of points and many other geometric problems (Gajentaan & Overmars, 1995) |
| APSP conjecture | all-pairs shortest paths with integer weights needs time | truly subcubic algorithms for negative-triangle detection and the other problems equivalent to APSP (Vassilevska Williams & Williams, 2010) |
The practical reading: when a problem is SETH-hard, as the edit distance of two arbitrary strings of a million characters is, stop hunting for an algorithm. Look for structure instead: a small distance allows time (Ukkonen, 1985; Myers's 1986 variant runs inside the diff tool), bit-parallelism gains a factor of the word size, and approximation helps when an estimate is enough.
A colleague is searching for an algorithm that computes the edit distance of two arbitrary strings of length . What does fine-grained complexity tell them?
- It is impossible, by a proven lower bound
- It would prove P = NP
- It would refute SETH, a widely believed but unproven conjecture, so it is very unlikely to exist
- Nothing: edit distance is already polynomial, so complexity theory has nothing to say
Show the answer
C. It would refute SETH, a widely believed but unproven conjecture, so it is very unlikely to exist
Backurs and Indyk (2015) showed that an algorithm for edit distance would give a algorithm for -SAT for every , refuting SETH. This is conditional evidence, not a proof.
Recognizing it
Once you know (or suspect) that the core of a problem is NP-hard, read the constraints for the way out:
- Tiny , at most about 10: try all permutations. At most about 20: DP over subsets.
- up to about 40 with sums or targets: meet in the middle.
- A small parameter beside a large ("at most changes", " special vertices" with ): FPT methods; kernelize, then branch, or run a DP over subsets of the special items only.
- Stated or hidden structure: trees, DAGs, bipartite graphs, intervals, grids of small width.
- A large, messy NP-hard core (timetables, routing with side constraints): encode for a SAT, MIP or CP solver, or run local search and certify it with a bound.
- A polynomial algorithm that is too slow ( with ): check whether the problem is SETH-, 3SUM- or APSP-hard before hunting for a better exponent.
| Problem, in brief | Signal | Technique | Cost |
|---|---|---|---|
| Shortest route from a depot through 15 required stops in a city graph of intersections | a few special vertices | Dijkstra from each stop, then Held–Karp over the 15 stops only | , about DP steps |
| Can 40 given weights be split into two groups of equal total? | , sums | meet in the middle: subset sums per half, sort one list, look up complements | |
| Choose at most servers so that every one of links has a chosen endpoint | small , vertex cover | Buss's kernel, then the bounded search tree | |
| Assign 300 exams to 30 time slots so that no student has two exams at once | graph coloring with side constraints | encode as CNF or MIP and run a solver | no guarantee; usually fast in practice |
| Maximum-weight set of employees with no manager–report pair, in an org chart | tree structure | tree DP, two values per person |
Common bugs.
- Exponential in the wrong variable: a DP over subsets of all vertices instead of the 15 special ones.
- Memory: a table of eight-byte entries takes 6.7 GB, while at it takes 168 MB.
- Kernel rules applied without lowering , or continued after the budget went negative.
- Meet in the middle that stores sums in a set when the task counts solutions: duplicates need a count per sum.
- A SAT encoding without the "at most one" clauses, which silently lets a vertex take two colors.
A graph has vertices and edges, and . Decide whether deleting at most vertices removes every edge. Which approach fits the limits?
- Try every set of at most vertices
- A bitmask DP over all subsets of vertices
- Repeatedly delete a vertex of maximum degree
- Buss's kernel, then the bounded search tree:
Show the answer
D. Buss's kernel, then the bounded search tree:
This is vertex cover with a small parameter. The kernel takes linear time and leaves at most edges; branching then costs about steps.
Key takeaways
- Exact exponential algorithms are chosen by input size: permutations up to about 10, DP over subsets up to about 20 (Held–Karp's instead of ), meet in the middle up to about 40, and pruned search beyond.
- A small parameter makes hard problems tractable: vertex cover in by a bounded search tree, after Buss's kernel leaves at most edges. Not every parameter helps: -clique is believed not to be FPT.
- Special structure (trees, bipartite graphs, DAGs, 2-CNF, bounded treewidth) turns many NP-hard problems polynomial; check that your class is not still hard, as planar 3-coloring is.
- Solvers (SAT, MIP, CP) take encoded NP-hard cores of real size; local search finds good solutions with no guarantee, and lower bounds certify how good they are.
- Fine-grained conjectures (SETH, 3SUM, APSP) explain why edit distance, 3SUM and all-pairs shortest paths resist polynomial speedups: look for structure, not a better exponent.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Which running time makes vertex cover parameterized by the cover size fixed-parameter tractable?
Show the answer
B.
FPT means with the degree of the polynomial independent of ; has that form. In the other options sits in the exponent of , or in the exponent.
A vertex has degree 12, and you are looking for a vertex cover of size at most . Why must that vertex be in it?
- Because high-degree vertices are always in minimum covers
- Because a cover without it would have to contain all 12 of its neighbors, more than 10 vertices
- Because Buss's rule says so for every vertex of degree at least
- It need not be: a cover of size 10 could avoid it
Show the answer
B. Because a cover without it would have to contain all 12 of its neighbors, more than 10 vertices
Each of its 12 edges must be covered; without the vertex itself, all 12 neighbors are needed, exceeding the budget of 10. So every cover of size at most 10 contains it.
Subset sum on numbers: what does meet in the middle do, and at what cost?
- It tries all subsets, but in parallel
- It lists the subset sums of each half, sorts one list and, for each sum in the other, searches for the complement: time
- It uses the dynamic program over target values
- It greedily takes the largest numbers that fit
Show the answer
B. It lists the subset sums of each half, sorts one list and, for each sum in the other, searches for the complement: time
A subset is a subset of the first half plus a subset of the second, so a solution is a pair of half-sums adding to the target. Listing and sorting sums per half replaces subsets (Horowitz & Sahni, 1974).
2-opt stops: no exchange of two edges shortens the tour. What do you know?
- The tour is optimal
- The tour is within a factor 2 of optimal
- The tour is a local optimum for 2-opt moves, and without a lower bound you know nothing about its distance from the optimum
- The tour has no crossing edges, so it is optimal
Show the answer
C. The tour is a local optimum for 2-opt moves, and without a lower bound you know nothing about its distance from the optimum
Local search guarantees only local optimality. On the 3 × 4 grid in this lesson, 2-opt stops at 1.069 times the optimum from both starting tours. To know how good a tour is, compare it with a lower bound such as the Held–Karp bound.
You must find a maximum-weight set of employees, no two of whom are in a direct manager–report relationship, in a company of 50,000. Which approach fits?
- Brute force over subsets
- An approximation algorithm, since independent set is NP-hard
- A tree DP over the org chart: for each person, the best weight of their subtree with and without them
- A SAT solver
Show the answer
C. A tree DP over the org chart: for each person, the best weight of their subtree with and without them
The org chart is a tree, and maximum-weight independent set on a tree is solved in time by keeping two values per vertex. NP-hardness on general graphs is irrelevant here.
Go deeper
- Parameterized Algorithms & Kernelization · Fixed-parameter tractability, bounded search trees and kernels.
- SAT Solvers in Practice · DPLL, conflict-driven clause learning, and why “NP-hard” is not “hopeless”.
- Fine-Grained Complexity · SETH, 3SUM and APSP: why some polynomial algorithms seem impossible to beat.
Further reading
- M. Cygan, F. V. Fomin, Ł. Kowalik, D. Lokshtanov, D. Marx, M. Pilipczuk, M. Pilipczuk & S. Saurabh, Parameterized Algorithms (Springer, 2015).
- F. V. Fomin & D. Kratsch, Exact Exponential Algorithms (Springer, 2010).
- J. Kleinberg & É. Tardos, Algorithm Design (Addison-Wesley, 2005), chapters 10 and 12.
- A. Biere, M. Heule, H. van Maaren & T. Walsh (eds.), Handbook of Satisfiability, 2nd ed. (IOS Press, 2021).