Simple Algorithm
Algorithms & Data Structures · Optimized · 24 min

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 (n≤10n \le 10), DP over subsets (n≤20n \le 20), meet in the middle (n≤40n \le 40), and pruned search beyond.
  • Prove that vertex cover can be solved in O(2k(n+m))O(2^k(n + m)) time by a bounded search tree, and shrink instances to k2k^2 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 (n−1)!/2(n - 1)!/2 tours, while the Held–Karp dynamic program over subsets fills (n−1) 2n−2(n - 1)\,2^{n-2} table entries, in O(2nn2)O(2^n n^2) time. Read the constraints with this course's rule of thumb, about 10810^8 simple operations per second (a rule of thumb, not a law):

Input sizeExact method that fitsExample
n≤10n \le 10–1111all permutations, O(n!)O(n!)brute-force TSP on 10 cities: 181,440 tours
n≤20n \le 20–2525DP over subsets, O(2nn)O(2^n n) to O(2nn2)O(2^n n^2)Held–Karp: TSP on 20 cities in under a second
n≤40n \le 40meet in the middle, O(2n/2n)O(2^{n/2} n)subset sum on 40 numbers: two lists of 220≈1062^{20} \approx 10^6 half-sums (Horowitz & Sahni, 1974)
largerbranch and bound: prune by feasibility and by boundsknapsack and TSP solvers that prune with LP bounds
The lessons Bitmask DP & the Held–Karp Algorithm, Meet in the Middle and Pruning & Branch and Bound develop each row.
Check your understanding

Brute force checks (n−1)!/2(n - 1)!/2 tours. For 20 cities, at 10810^8 tours per second, how long does it take?

  1. About a second
  2. About an hour
  3. About 19 years
  4. Longer than the age of the universe
Show the answer

C. About 19 years

19!/2≈6.1×101619!/2 \approx 6.1 \times 10^{16} tours take about 6.1×1086.1 \times 10^8 seconds: 19 years. Held–Karp compares about 4.5×1074.5 \times 10^7 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 k=20k = 20 in a graph with a million edges. Trying all (nk)\binom{n}{k} candidate covers is hopeless. A fixed-parameter tractable algorithm runs in f(k)⋅nO(1)f(k)\cdot n^{O(1)} time, with all the exponential growth in kk. The simplest technique is a bounded search tree: every edge uvuv forces uu or vv into the cover, so branch on the two.

python
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 None

Each call deletes the edges of the chosen vertex in O(m)O(m) time and lowers kk by one. Tested against brute force on 1,500 random graphs.

DerivationProof
  1. C∋w, ∣C∣≤k  ⇒  C∖{w} covers the edges avoiding w and has size≤k−1C \ni w,\ \abs{C} \le k\ \ \Rightarrow\ \ C \setminus \{w\} \text{ covers the edges avoiding } w \text{ and has size} \le k - 1

    Correct, by induction on kk. Every vertex cover contains uu or vv. If a cover CC with ∣C∣≤k\abs{C} \le k contains w∈{u,v}w \in \{u, v\}, then C∖{w}C \setminus \{w\} covers every edge that avoids ww, so the recursive call for ww, with budget k−1k - 1, succeeds. Conversely, anything returned is a cover of size at most kk.

  2. #calls ≤ 1+2+4+⋯+2k = 2k+1−1\#\text{calls}\ \le\ 1 + 2 + 4 + \dots + 2^k\ =\ 2^{k+1} - 1

    Bounded. Each call makes at most two recursive calls and lowers kk, so the recursion tree is binary with depth at most kk:

  3. O(2k (n+m))O\big(2^k\,(n + m)\big)

    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 kk belongs to every cover of size at most kk, because a cover without it would need all its more than kk neighbors. Take it, lower kk, and repeat. Afterwards every degree is at most kk, so kk vertices cover at most k2k^2 edges: if more remain, the answer is no; otherwise at most k2k^2 edges are left, however large the original graph.

python
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 k=3k = 3: 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.

Predict before you look

After Buss's rule with k=20k = 20, at most how many edges can a yes-instance have left?

Show the answer

400

Every remaining degree is at most k=20k = 20, so 20 cover vertices touch at most 20⋅20=40020 \cdot 20 = 400 edges. The search tree then runs on at most 400 edges, whatever the original size: O(n+m+2kk2)O(n + m + 2^k k^2) time in all.

Smarter branching lowers the base of the exponential: branch on a vertex vv of degree at least 3, putting either vv or all of its neighbors into the cover. The best published bounds are O(1.2738k+kn)O(1.2738^k + kn) (Chen, Kanj & Xia, 2010) and about 1.2529k1.2529^k (Harris & Narayanaswamy, 2024). The Optimal lesson Parameterized Algorithms & Kernelization derives such bounds, and explains why kk-clique, solvable in nO(k)n^{O(k)} 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:

ProblemIn generalPolynomial whenHow
Maximum independent set, minimum vertex coverNP-hardthe graph is a treetree DP: each vertex in or out, O(n)O(n)
Minimum vertex coverNP-hardthe graph is bipartiteKönig's theorem: it equals a maximum matching, found with a flow algorithm
Graph coloringNP-hard for 3 colorsthe graph is an interval graphgreedy coloring by left endpoint is optimal
Longest pathNP-hardthe graph is a DAGdynamic programming in topological order
SatisfiabilityNP-complete for 3-CNFevery clause has 2 literals2-SAT through strongly connected components, O(n+m)O(n + m)
Independent set, coloring, Hamiltonian cycle, …NP-hardthe treewidth is at most wwDP over a tree decomposition in f(w)⋅nf(w)\cdot n time (Courcelle's theorem)
Planar graphs sit in between: many problems stay NP-hard on them, but approximation schemes (Baker, 1994) and algorithms subexponential in the parameter, such as 2O(k) nO(1)2^{O(\sqrt k)}\,n^{O(1)} for planar vertex cover, exist.
Check your understanding

Which of these special cases is still NP-complete?

  1. Vertex cover in a bipartite graph
  2. Maximum independent set in a tree
  3. Satisfiability of a 2-CNF formula
  4. 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:

python
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 variables

One variable per (vertex, color) pair: nn "some color" clauses, 3n3n "at most one" clauses and 3m3m conflict clauses. The Petersen graph gives 85 clauses over 30 variables; the formula for K4K_4 is unsatisfiable, as brute force over its 2122^{12} 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 O(n2)O(n^2), 3SUM in O(n2)O(n^2), all-pairs shortest paths in O(n3)O(n^3). Fine-grained complexity explains this the way NP-completeness explains exponential time: through reductions from a few problems conjectured to be hard.

Conjecture (unproven)StatementWhat it rules out
SETH (Impagliazzo & Paturi, 2001)for every ε>0\varepsilon > 0 there is a kk such that kk-SAT on nn variables needs more than 2(1−ε)n2^{(1-\varepsilon)n} timeedit distance and longest common subsequence in O(n2−ε)O(n^{2-\varepsilon}) (Backurs & Indyk, 2015; Abboud, Backurs & Vassilevska Williams, 2015)
3SUM conjecturedeciding whether nn integers contain a+b+c=0a + b + c = 0 needs n2−o(1)n^{2-o(1)} timeO(n2−ε)O(n^{2-\varepsilon}) algorithms for collinearity of points and many other geometric problems (Gajentaan & Overmars, 1995)
APSP conjectureall-pairs shortest paths with integer weights needs n3−o(1)n^{3-o(1)} timetruly subcubic algorithms for negative-triangle detection and the other problems equivalent to APSP (Vassilevska Williams & Williams, 2010)
Each reduction says: an algorithm faster by a polynomial factor would refute the conjecture. The Optimal lesson Fine-Grained Complexity proves the first link.

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 O(n1.9)O(n^{1.9}) algorithm. Look for structure instead: a small distance dd allows O(nd)O(nd) 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.

Check your understanding

A colleague is searching for an O(n1.9)O(n^{1.9}) algorithm that computes the edit distance of two arbitrary strings of length nn. What does fine-grained complexity tell them?

  1. It is impossible, by a proven lower bound
  2. It would prove P = NP
  3. It would refute SETH, a widely believed but unproven conjecture, so it is very unlikely to exist
  4. 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 O(n2−ε)O(n^{2-\varepsilon}) algorithm for edit distance would give a 2(1−δ)n2^{(1-\delta)n} algorithm for kk-SAT for every kk, 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 nn, at most about 10: try all permutations. At most about 20: DP over subsets.
  • nn up to about 40 with sums or targets: meet in the middle.
  • A small parameter beside a large nn ("at most k≤20k \le 20 changes", "k≤15k \le 15 special vertices" with n≤105n \le 10^5): FPT methods; kernelize, then branch, or run a DP over subsets of the kk 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 (O(n2)O(n^2) with n=106n = 10^6): check whether the problem is SETH-, 3SUM- or APSP-hard before hunting for a better exponent.
Problem, in briefSignalTechniqueCost
Shortest route from a depot through 15 required stops in a city graph of 10410^4 intersectionsa few special verticesDijkstra from each stop, then Held–Karp over the 15 stops onlyO(k mlog⁡n+2kk2)O(k\,m\log n + 2^k k^2), about 7×1067 \times 10^6 DP steps
Can 40 given weights be split into two groups of equal total?n=40n = 40, sumsmeet in the middle: 2202^{20} subset sums per half, sort one list, look up complementsO(2n/2 n)O(2^{n/2}\,n)
Choose at most k=20k = 20 servers so that every one of 10510^5 links has a chosen endpointsmall kk, vertex coverBuss's kernel, then the bounded search treeO(n+m+2kk2)O(n + m + 2^k k^2)
Assign 300 exams to 30 time slots so that no student has two exams at oncegraph coloring with side constraintsencode as CNF or MIP and run a solverno guarantee; usually fast in practice
Maximum-weight set of employees with no manager–report pair, in an org charttree structuretree DP, two values per personO(n)O(n)
In each row the escape comes from the instance, not from a better algorithm for the general problem.

Common bugs.

  • Exponential in the wrong variable: a DP over subsets of all 10510^5 vertices instead of the 15 special ones.
  • Memory: a table of 225×252^{25} \times 25 eight-byte entries takes 6.7 GB, while at n=20n = 20 it takes 168 MB.
  • Kernel rules applied without lowering kk, 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.
Check your understanding

A graph has n≤105n \le 10^5 vertices and m≤2×105m \le 2 \times 10^5 edges, and k≤15k \le 15. Decide whether deleting at most kk vertices removes every edge. Which approach fits the limits?

  1. Try every set of at most kk vertices
  2. A bitmask DP over all subsets of vertices
  3. Repeatedly delete a vertex of maximum degree
  4. Buss's kernel, then the bounded search tree: O(n+m+2kk2)O(n + m + 2^k k^2)
Show the answer

D. Buss's kernel, then the bounded search tree: O(n+m+2kk2)O(n + m + 2^k k^2)

This is vertex cover with a small parameter. The kernel takes linear time and leaves at most k2=225k^2 = 225 edges; branching then costs about 215⋅225≈7×1062^{15} \cdot 225 \approx 7 \times 10^6 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 O(2nn2)O(2^n n^2) instead of n!n!), meet in the middle up to about 40, and pruned search beyond.
  • A small parameter makes hard problems tractable: vertex cover in O(2k(n+m))O(2^k(n + m)) by a bounded search tree, after Buss's kernel leaves at most k2k^2 edges. Not every parameter helps: kk-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.

Question 1

Which running time makes vertex cover parameterized by the cover size kk fixed-parameter tractable?

  1. O(nk)O(n^k)
  2. O(1.28k+kn)O(1.28^k + kn)
  3. O(kn)O(k^n)
  4. O(nk)O(n^{\sqrt k})
Show the answer

B. O(1.28k+kn)O(1.28^k + kn)

FPT means f(k)⋅nO(1)f(k)\cdot n^{O(1)} with the degree of the polynomial independent of kk; 1.28k+kn1.28^k + kn has that form. In the other options kk sits in the exponent of nn, or nn in the exponent.

Question 2

A vertex has degree 12, and you are looking for a vertex cover of size at most k=10k = 10. Why must that vertex be in it?

  1. Because high-degree vertices are always in minimum covers
  2. Because a cover without it would have to contain all 12 of its neighbors, more than 10 vertices
  3. Because Buss's rule says so for every vertex of degree at least kk
  4. 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.

Question 3

Subset sum on n=40n = 40 numbers: what does meet in the middle do, and at what cost?

  1. It tries all 2402^{40} subsets, but in parallel
  2. It lists the 2202^{20} subset sums of each half, sorts one list and, for each sum in the other, searches for the complement: O(2n/2 n)O(2^{n/2}\,n) time
  3. It uses the O(nT)O(nT) dynamic program over target values
  4. It greedily takes the largest numbers that fit
Show the answer

B. It lists the 2202^{20} subset sums of each half, sorts one list and, for each sum in the other, searches for the complement: O(2n/2 n)O(2^{n/2}\,n) 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 220≈1062^{20} \approx 10^6 sums per half replaces 240≈10122^{40} \approx 10^{12} subsets (Horowitz & Sahni, 1974).

Question 4

2-opt stops: no exchange of two edges shortens the tour. What do you know?

  1. The tour is optimal
  2. The tour is within a factor 2 of optimal
  3. The tour is a local optimum for 2-opt moves, and without a lower bound you know nothing about its distance from the optimum
  4. 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.

Question 5

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?

  1. Brute force over subsets
  2. An approximation algorithm, since independent set is NP-hard
  3. A tree DP over the org chart: for each person, the best weight of their subtree with and without them
  4. 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 O(n)O(n) time by keeping two values per vertex. NP-hardness on general graphs is irrelevant here.

Go deeper

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).