Sub topic 18
Handling NP-Hard Problems in Real Systems
This chapter assumes you know what NP-hard and NP-complete mean, that you can read Python, and that you know basic graph terms and Big-O notation. Earlier chapters showed that no polynomial-time algorithm is known for any NP-complete problem. This chapter covers what engineers do when a real system needs to solve one anyway.
The key point is that NP-hardness is a statement about the worst case over all inputs. Your system never sees all inputs. It sees your inputs, at your sizes, under your time budget, and that leaves several ways forward.
The Main Strategies
| Strategy | What you give up | What you keep | Typical example |
|---|---|---|---|
| Exact solver (SAT, ILP, branch and bound) | Guaranteed fast running time | Optimal or exact answers | Scheduling, hardware verification |
| Approximation algorithm | Optimality | Provable quality bound, polynomial time | Vertex Cover within a factor of 2 |
| Heuristics and local search | Any guarantee | Speed and usually good answers | Large routing problems |
| Special cases and structure | Generality | Exact answers in polynomial time | Trees, bipartite graphs, small parameters |
| Pseudo-polynomial algorithms | Speed when numbers are large | Exact answers when numbers are small | Subset Sum with small targets |
Exact Solvers: Reduce to SAT or ILP
Modern SAT solvers use conflict-driven clause learning (CDCL). They routinely solve industrial formulas with millions of variables and clauses. Integer linear programming (ILP) solvers such as Gurobi, CPLEX, HiGHS, and CBC do the same kind of work for problems with numeric objectives.
Reductions are the practical tool here. Cook-Levin says any NP problem can be encoded as SAT. In practice, you encode your problem as CNF clauses or linear constraints and let a tuned solver search. Years of engineering go into these solvers, and you get all of it without writing a search algorithm yourself.
Approximation Algorithms
An approximation algorithm runs in polynomial time and returns a solution whose cost is provably within some factor of optimal. Vertex Cover has a simple 2-approximation. Go through the edges, and whenever an edge has neither endpoint covered, add both endpoints.
def approx_vertex_cover(edges):
"""Returns a vertex cover at most twice the size of the minimum one."""
cover = set()
for u, v in edges:
if u not in cover and v not in cover:
cover.add(u)
cover.add(v)
return cover
edges = [(1, 2), (2, 3), (3, 4), (4, 1), (1, 3)]
print(approx_vertex_cover(edges)) # {1, 2, 3, 4}; the optimum is {1, 3}Here is why the bound holds. The edges that trigger an addition share no endpoints, so they form a matching M. Any vertex cover needs at least one endpoint from each edge of M, so OPT ≥ |M|. The algorithm adds exactly 2|M| vertices, so its cover is at most 2 · OPT.
How well a problem can be approximated depends on the problem. NP-completeness does not tell you:
- Metric TSP has a 1.5-approximation (Christofides).
- General TSP, where distances need not satisfy the triangle inequality, has no constant-factor approximation unless P = NP.
- Knapsack can be approximated within any factor 1 + ε you choose, with a polynomial-time approximation scheme.
- Maximum Clique cannot be approximated within n^(1−ε) unless P = NP.
Exploiting Structure and Parameters
Many NP-hard problems become easy on restricted inputs. Vertex Cover is solvable in polynomial time on trees and on bipartite graphs, where König's theorem links it to maximum matching. Graph coloring with two colors is in P, as an earlier chapter showed.
Fixed-parameter tractable (FPT) algorithms confine the exponential cost to a parameter k that is small in your inputs. For Vertex Cover, every edge (u, v) must have u or v in the cover. Branching on those two choices gives a search tree of depth at most k:
def has_vertex_cover(edges, k):
"""Decides whether a cover of size <= k exists, in O(2^k * |E|) time."""
if not edges:
return True
if k == 0:
return False
u, v = edges[0]
without_u = [e for e in edges if u not in e]
without_v = [e for e in edges if v not in e]
return has_vertex_cover(without_u, k - 1) or has_vertex_cover(without_v, k - 1)
edges = [(1, 2), (2, 3), (3, 4), (4, 1), (1, 3)]
print(has_vertex_cover(edges, 2)) # True
print(has_vertex_cover(edges, 1)) # FalseWith k = 20, the 2^k factor is about a million, so the algorithm stays practical on graphs with millions of edges. Brute force over all subsets of n vertices would not be.
The pseudo-polynomial dynamic program for Subset Sum from an earlier chapter is another case of this idea. There, the "parameter" is the size of the target value.
Heuristics and Local Search
When instances are huge and approximate answers are acceptable, engineers use greedy construction followed by local improvement. Examples include 2-opt for TSP, simulated annealing, tabu search, and genetic algorithms. These methods have no worst-case guarantee, but they often get within a few percent of optimal in practice. To evaluate them honestly, compare against exact solutions on small instances or against lower bounds, such as linear programming relaxations, on large ones.
Failure Modes and Gotchas
- Assuming hardness without checking. Engineers sometimes label a problem NP-hard when their version has extra structure that puts it in P. Check whether your graphs are trees or planar, and whether your parameter is bounded.
- Assuming easiness from small tests. An exponential algorithm that finishes in 50 ms on 20 items may take hours on 40. Benchmark at production sizes, and also above them.
- Confusing the decision and optimization versions. A solver that decides "is there a cover of size ≤ k?" still needs search, such as binary search on k plus self-reduction, before it can return an actual cover.
- Missing timeouts. Solver running times vary a lot between instances of the same size. A single bad instance can stall a request path.
- Approximation ratios that don't apply. A ratio proven for metric TSP says nothing about asymmetric or non-metric distances.
Exercise
The 2-approximation for Vertex Cover adds both endpoints of uncovered edges. Give a graph where it returns exactly twice the optimum.
Show answer
A single edge (1, 2) works: the algorithm returns {1, 2} while the optimum is {1} or {2}. More generally, any perfect matching of n/2 disjoint edges gives a cover of size n versus an optimum of n/2.
Exercise
Your service must find minimum vertex covers in graphs with 100,000 edges, where the optimal cover always has at most 15 vertices. Which strategy fits, and what is its rough cost?
Show answer
Use the fixed-parameter branching algorithm. Its running time is O(2^k · |E|), about 32,768 × 100,000 ≈ 3.3 × 10^9 basic steps in the worst case. Kernelization rules, such as forcing any vertex with degree greater than k into the cover, usually cut this down a lot. Search k = 0, 1, 2, ... to find the minimum.
Exercise
Why does NP-hardness of a problem not imply that a SAT solver will be slow on your instances?
Show answer
NP-hardness is a worst-case statement over all inputs. Real instances often have structure that CDCL solvers exploit through clause learning and propagation, so they can be solved quickly even though some instances of the same size are intractable.