Module contents
Lesson 30 of 33Advanced 115 min

Coping with NP-hardness: exact, parameterized and fine-grained algorithms

NP-hardness does not end the conversation. Study exact algorithms improving on brute force, including branch and bound and meet-in-the-middle; parameterized complexity through bounded search trees, kernelization and FPT; ETH and SETH; and fine-grained complexity, which explains why polynomial-time problems such as edit distance and all-pairs shortest paths resist substantial improvement.

After this lesson you can

  • Implement branch and bound with relaxation bounds and measure the effect of the quality of the bound.
  • Solve the subset sum with meet-in-the-middle and analyze its cost.
  • Design FPT algorithms and kernels for vertex cover and related problems.
  • Use ETH and SETH to obtain conditional lower bounds.
  • Explain the fine-grained reduction connecting edit distance to SETH.

Before you start

Motivation: NP-hard is not the end of the conversation

The lesson on NP-completeness ends with a verdict: if your problem is NP-hard, do not expect a polynomial-time algorithm. Yet NP-hard problems are solved exactly every day. Hardware verification issues millions of SAT queries with hundreds of thousands of variables. Airlines assign crews through integer programs with millions of variables. In 2006, Concorde proved optimality of a traveling-salesperson tour through 85 90085\,900 cities, instance pla85900 from an actual circuit-manufacturing problem. None contradicts theory: theory concerns the worst case over all inputs of size nn, whereas the inputs that matter have structure.

This lesson explains how to exploit that structure and, when it is absent, prove that substantially better algorithms are unlikely. There are four distinct questions:

  1. How much better than brute force? Enumerating 2n2^n subsets or n!n! permutations is the starting point. Branch and bound discards entire regions using bounds; meet-in-the-middle replaces 2n2^n by 2n/22^{n/2}; and a careful branching analysis improves maximum independent set from 2n2^n to 1.38n1.38^n.
  2. Where is the explosion? If exponential dependence is confined to a small parameter kk, such as solution size or graph treewidth, an algorithm taking f(k)⋅nO(1)f(k)\cdot n^{\bigO(1)} can be practical despite NP-hardness. This is parameterized complexity. One of its most useful tools is kernelization: polynomial-time preprocessing reducing any instance to a core whose size is bounded by kk.
  3. Can we do better still? Answering ‘probably not’ requires a stronger assumption than P ≠\neq NP: the Exponential Time Hypothesis, ETH, and its strong version, SETH, yield precise conditional lower bounds.
  4. What about polynomial-time problems? Edit distance has had a quadratic algorithm since 1974, and all-pairs shortest paths a cubic algorithm since Floyd-Warshall. Fine-grained complexity uses the same hypotheses to explain why those exponents resist improvement. The reduction establishing this for edit distance is fundamentally another meet-in-the-middle construction.

Branching and pruning

Backtracking with bounds

Consider 0/1 knapsack: nn items with positive integer weights wiw_i and values viv_i, and capacity CC. Seek max⁡∑ivixi\max \sum_i v_i x_i subject to ∑iwixi≤C\sum_i w_i x_i \le C and xi∈{0,1}x_i \in \{0, 1\}. Exhaustive search traverses a depth-nn binary tree: level dd decides whether to take item dd, and each leaf represents one of 2n2^n assignments. Backtracking already prunes something: once accumulated weight exceeds CC, no extension is feasible and the branch is abandoned. This is insufficient, however, because almost every small subset fits into a half-full knapsack.

The decisive question at each node is how much value could possibly be gained by completing its partial decision. If this cannot exceed the best known solution, discard the entire subtree.

Correctness is immediate: a pruned node contains no solution better than z∗z^*, since all its solutions have value at most fˉ(ν)≤z∗\bar f(\nu) \le z^*. Efficiency is not immediate; it depends entirely on bound tightness. The trivial bound fˉ=∞\bar f = \infty prunes nothing. With the exact bound fˉ(ν)=max⁡Fνf\bar f(\nu) = \max_{F_\nu} f, exploring the child with the largest bound first leads directly to an optimum, and every other node is pruned when visited. Computing that bound, however, is as hard as the original problem. Practical engineering lies between these extremes.

At a knapsack node where some items have already been decided, with accumulated value VV and weight WW, there are two natural bounds:

  • Trivial bound: V+∑i unassignedviV + \sum_{i \text{ unassigned}} v_i, as though every remaining item could fit.
  • Fractional bound: the optimum of the subproblem’s linear relaxation, allowing each undecided item to be taken fractionally, xi∈[0,1]x_i \in [0, 1].

The linear relaxation has a closed-form solution, which makes knapsack the textbook example.

Proof

Let xx be an optimal LP solution. If ∑iwixi<C\sum_i w_i x_i < C and some xi<1x_i < 1, increasing xix_i strictly improves value. Thus an optimum either takes everything or fills capacity. Suppose i<ji < j with xi<1x_i < 1 and xj>0x_j > 0. Move weight from jj to ii: for small ε>0\eps > 0, set xi←xi+ε/wix_i \gets x_i + \eps/w_i and xj←xj−ε/wjx_j \gets x_j - \eps/w_j. Total weight stays unchanged, while value changes by ε (vi/wi−vj/wj)≥0\eps\,(v_i/w_i - v_j/w_j) \ge 0. Repeating this exchange without worsening the solution yields one where no denser item is incomplete while a less-dense item is taken at all: exactly the stated greedy solution. Hence the greedy solution is also optimal.

∎

This is an exchange argument of the kind used in greedy algorithms. It gives a bound computable in O(n)\bigO(n) per node, or O(log⁡n)\bigO(\log n) using prefix sums and binary search. Its validity is a general property of relaxations: the integer feasible set lies inside the continuous one, so the continuous maximum is at least as large. This is the same convex-relaxation idea used in optimization, here serving exact search.

Integer values let us tighten the test: every integer solution’s value is integral, so prune whenever ⌊fˉ(ν)⌋≤z∗\lfloor \bar f(\nu) \rfloor \le z^*.

InteractiveBranch-and-bound tree
Search space: level d decides item d (take to the left, leave to the right)
  • branched
  • pruned by bound (with its shadow)
  • infeasible
  • leaf
  • improvement
  • path to the best solution
node 53 / 53
Current node (level 1): knapsack and fractional fill
36293513162733%selected: value 0, weight 0capacity C = 138fractional bound 169.0 · trivial bound 277
d0
v 33
w 23
d1
v 36
w 26
d2
v 29
w 22
d3
v 35
w 28
d4
v 13
w 11
d5
v 16
w 14
d6
v 27
w 24
d7
v 40
w 40
d8
v 17
w 18
d9
v 16
w 17
d10
v 26
w 29
d11
v 22
w 25
Nodes visited in this instance (log scale)
110¹10²10³10⁴complete treeNone · input order5 239None · density5 897Trivial · input order1 413Trivial · density1 929Fractional · input order237Fractional · density53
Bound
Item order
Traversal
12
Visited nodes53 of 8 191
Pruned by bound7
Infeasible (weight > C)17
Leaves reached3
Incumbent176
Optimal (DP)176
Done: the optimum is 176 (dynamic programming gives 176), proved after visiting 53 of the complete tree’s 8 191 nodes.
A knapsack with 12 items and capacity 138. The map above is the full search tree, with 8 1918\,191 nodes, drawn by levels: at level dd the dd-th item is decided (take to the left, leave to the right) and each node occupies its interval. The visited nodes are painted in the order of the search; a pruned node casts a shadow downward, the sub-tree that is no longer visited. Below, the knapsack of the current node: what has already been taken, in blue, and the greedy fractional filling that gives the bound, with the last item split. At the bottom, the nodes visited by the six combinations of bound and order in this same instance. Change from fractional bound to trivial and none, and from density order to input order; test the 'best first' traversal and other instances.

What you should have observed:

  • The fractional bound with density ordering proves optimality in 53 nodes. The optimum is 176 and the root bound is already 177.75177.75: the LP relaxation differs by only 1.751.75 units. Almost any branch departing from the greedy solution drops the bound below 177, whose integer part no longer exceeds 176, and is pruned within one or two levels.
  • The trivial bound needs 1 9291\,929 nodes; no value bound needs 5 8975\,897. The root’s trivial bound is the sum of all values, 310, so pruning begins only after enough items have been excluded. Without a value bound, only over-capacity nodes are discarded, and all 2 0482\,048 feasible leaves are reached. A useful bound can save two orders of magnitude; a poor one may save none.
  • Ordering matters, but only with a good bound. With the fractional bound, deciding dense items first reduces the node count from 237 to 53: the first explored branch nearly matches the greedy solution, giving a strong incumbent immediately. With the trivial bound, the same ordering makes matters worse, from 1 4131\,413 to 1 9291\,929, because that bound ignores capacity and cannot exploit a strong incumbent.
  • Best-first search visits even fewer nodes: 41 with density ordering and 33 with input ordering, where ordering scarcely matters anymore, because it always expands the largest-bound node. The price is retaining the entire open frontier in memory. Depth-first search uses O(n)\bigO(n) memory, so industrial solvers combine both strategies.

What real solvers do

A mixed-integer programming solver such as CPLEX, Gurobi, HiGHS or SCIP uses branch and bound with the full integer problem’s LP relaxation as its bound. Dual simplex reuses the parent’s basis. Three additions matter: cutting planes, inequalities valid for integer solutions that remove fractional vertices and improve the bound, giving branch and cut; primal heuristics, finding strong incumbents early; and presolve, reduction rules simplifying the instance before search. Modern SAT solvers descended from DPLL also backtrack, but use unit propagation and clause learning rather than a numerical bound. Each conflict produces a clause pruning future branches that would repeat the same mistake. Game-search alpha-beta pruning is branch and bound with two incumbents, one per player.

Meet-in-the-middle

Subset sum asks whether some subset of a1,…,ana_1, \dots, a_n sums exactly to TT. It is NP-complete but admits pseudopolynomial time O(nT)\bigO(nT) through dynamic programming over capacity. With large numbers, such as 60-bit integers, TT is astronomical and enumeration remains. Enumerating 2n2^n subsets costs 2n2^n. There is a much better approach.

Proof

Split the numbers into A={a1,…,a⌊n/2⌋}A = \{a_1, \dots, a_{\lfloor n/2 \rfloor}\} and the remainder BB. Every subset SS uniquely decomposes as SA∪SBS_A \cup S_B, with SA⊆AS_A \subseteq A and SB⊆BS_B \subseteq B, and its sum is σ(SA)+σ(SB)\sigma(S_A) + \sigma(S_B). Generate lists LAL_A and LBL_B containing the 2⌊n/2⌋2^{\lfloor n/2\rfloor} and 2⌈n/2⌉2^{\lceil n/2\rceil} sums of the two halves, then sort LBL_B. For each s∈LAs \in L_A, binary-search for T−sT - s in LBL_B. A subset summing to TT exists exactly when a search succeeds. Doubling generates the lists in O(2n/2)\bigO(2^{n/2}) time; sorting costs O(2n/2log⁡2n/2)=O(2n/2 n)\bigO(2^{n/2}\log 2^{n/2}) = \bigO(2^{n/2}\,n), as do the searches. Memory consists of the two lists.

∎

Two refinements help. The lists are already sorted if generated by merging: sums for {a1,…,aj}\{a_1, \dots, a_j\} are the merge of the sums for {a1,…,aj−1}\{a_1, \dots, a_{j-1}\} and those same sums shifted by aja_j, two sorted lists. Total generation cost is ∑j2j=O(2n/2)\sum_j 2^j = \bigO(2^{n/2}). Two pointers traversing LAL_A upward and LBL_B downward then make the whole algorithm O(2n/2)\bigO(2^{n/2}). A hash table on LBL_B removes sorting altogether, trading worst-case cost for expected cost.

Memory does not improve: 2n/22^{n/2} sums are stored. At n=60n = 60, each list contains 2302^{30} eight-byte integers, taking 8 GiB. Schroeppel and Shamir (1981) reduced memory to O(2n/4)\bigO(2^{n/4}) without increasing time by splitting into four quarters and generating each half’s sums in order using two heaps, without storing them all. Whether subset sum admits O(2(1/2−ε)n)\bigO(2^{(1/2 - \eps)n}) has been open since 1974.

The general pattern: when a solution splits into two parts interacting only through a simple condition, such as a sum, intermediate state or ciphertext, enumerate both halves and join them using a data structure. Cost changes from ∣X∣⋅∣Y∣|X|\cdot|Y| to ∣X∣+∣Y∣|X| + |Y| plus the join. This will reappear unexpectedly at the end: the SAT reduction underlying fine-grained complexity is itself meet-in-the-middle.

Exact exponential algorithms

When no small parameter is available, the question is the exponential base. To suppress polynomial factors, write O∗(cn)\bigO^*(c^n), meaning O(cn nO(1))\bigO(c^n\,n^{\bigO(1)}). Since cnn10=O((c+ε)n)c^n n^{10} = \bigO((c + \eps)^n) for every ε>0\eps > 0, the base is what matters. You already know one example: Held-Karp solves traveling salesperson in O∗(2n)\bigO^*(2^n) rather than O∗(n!)\bigO^*(n!). Another example, maximum independent set, illustrates the field’s central technique.

Branching with a measure

Brute force for independent set tests 2n2^n subsets. A branching algorithm proceeds as follows:

  1. If a vertex uu has degree 0 or 1, take it and delete uu and its neighbor. This is safe: if an optimum contains the neighbor ww, replacing ww with uu gives another optimum because uu has no other neighbors.
  2. If every vertex has degree 2, the graph is a disjoint union of cycles. A cycle of length LL contributes ⌊L/2⌋\lfloor L/2 \rfloor.
  3. Otherwise, some vertex vv has degree at least 3. Branch: either vv is excluded, deleting vv and leaving n−1n - 1 vertices, or it is included, deleting vv and its neighbors and leaving at most n−4n - 4.

Let T(n)T(n) count worst-case search-tree leaves. Step 3 gives T(n)≤T(n−1)+T(n−4)T(n) \le T(n-1) + T(n-4); steps 1 and 2 do not branch.

Proof

The function g(x)=∑ix−tig(x) = \sum_i x^{-t_i} is continuous and strictly decreasing on (0,∞)(0, \infty), tending to ∞\infty at 00 and to 00 at ∞\infty. Since g(1)=r≥2>1g(1) = r \ge 2 > 1, there is exactly one root α>1\alpha > 1 of g(x)=1g(x) = 1. Choose cc such that T(m)≤c αmT(m) \le c\,\alpha^m for m≤tmax⁡m \le t_{\max}. Inductively, if the bound holds for every m<nm < n, then T(n)≤∑ic αn−ti=c αng(α)=c αnT(n) \le \sum_i c\,\alpha^{n - t_i} = c\,\alpha^n g(\alpha) = c\,\alpha^n.

∎

For (1,4)(1, 4) the equation is x4=x3+1x^4 = x^3 + 1, with root α≈1.3803\alpha \approx 1.3803. Polynomial work per node makes the three-rule algorithm O∗(1.3803n)\bigO^*(1.3803^n): at n=100n = 100, compare 1.38100≈10141.38^{100} \approx 10^{14} with 2100≈10302^{100} \approx 10^{30}. The vector (1,4)(1, 4) is the branching vector. Improving such an algorithm means finding rules guaranteeing better vectors: choosing a vertex of degree at least 4, for example, gives vector (1,5)(1, 5) and α≈1.3247\alpha \approx 1.3247.

The decisive refinement changed what is measured. Instead of counting vertices, Fomin, Grandoni and Kratsch (2009) weight each vertex by degree: a degree-2 vertex costs less than a degree-5 vertex because it is easier to eliminate. They analyze the recurrence in this measure. This measure-and-conquer method barely changes the algorithm but proves O(1.2201n)\bigO(1.2201^n) with polynomial memory. Xiao and Nagamochi (2017) reduced this to O(1.1996n)\bigO(1.1996^n). In the same spirit, Schöning’s random walk (1999) solves 3-SAT in O∗((4/3)n)\bigO^*((4/3)^n), and PPSZ variants fall below 1.31n1.31^n.

Parameterized complexity

The preceding exponential algorithms depend on nn, the size of the whole input. Often a much smaller quantity captures the actual difficulty: desired solution size, graph treewidth, or the number of variables appearing in many constraints. Parameterized complexity, developed by Downey and Fellows in the 1990s, studies algorithms whose exponential dependence is confined to that quantity.

The difference between FPT and XP can determine whether an instance is solvable in practice. With n=106n = 10^6 and k=20k = 20, 2kn≈10122^k n \approx 10^{12} operations correspond to about a quarter of an hour, whereas nk=10120n^k = 10^{120} would never finish. The canonical example is vertex cover: does some S⊆VS \subseteq V with ∣S∣≤k\abs{S} \le k touch every edge?

The idea fits in one line: choose any uncovered edge uvuv. Every cover contains uu or vv, so branch on these alternatives, each with budget k−1k - 1. The tree has depth kk and at most 2k2^k leaves. A guided exercise gives the complete proof. The key point is that the parameter bounds the tree’s depth, rather than graph size.

Richer branching gives smaller bases. If vertex vv has degree at least 3, either vv belongs to the cover or all its neighbors do; otherwise the edge to an omitted neighbor is uncovered. This gives branching vector (1,3)(1, 3) and base α≈1.4656\alpha \approx 1.4656, the root of x3=x2+1x^3 = x^2 + 1. If every degree is at most 2, solve the disjoint paths and cycles directly. Much finer case analysis led Chen, Kanj and Xia (2010) to O(1.2738k+kn)\bigO(1.2738^k + kn).

The parameter is everything

A set SS is a vertex cover exactly when V∖SV \setminus S is independent: the same problem, but with the parameter changing from kk to n−kn - k. Yet independent set parameterized by solution size does not appear to be FPT. Downey and Fellows organized these problems in the W hierarchy, FPT⊆W[1]⊆W[2]⊆⋯⊆XP\mathrm{FPT} \subseteq \mathrm{W}[1] \subseteq \mathrm{W}[2] \subseteq \cdots \subseteq \mathrm{XP}, with parameterized reductions preserving a bound on the parameter. Clique and independent set parameterized by kk are W[1]-complete; dominating set is W[2]-complete. All lie in XP by trying (nk)\binom{n}{k} subsets. The conjecture FPT≠W[1]\mathrm{FPT} \neq \mathrm{W}[1] plays the role that P ≠\neq NP plays in classical complexity. Below, ETH gives a quantitative version: clique cannot be solved in f(k) no(k)f(k)\,n^{o(k)}.

Kernelization

An even simpler FPT approach to vertex cover than the search tree explains why industrial solver preprocessing works so well.

Proof

Given a kernel, compute it in polynomial time, then solve the size-g(k)g(k) result with any algorithm: cost is polynomial plus a function of kk. Conversely, let AA run in f(k) ncf(k)\,n^c time. If n≥f(k)n \ge f(k), AA takes at most nc+1n^{c+1} time, which is polynomial: run it and return a constant-sized trivial instance with the same answer. If n<f(k)n < f(k), the original instance already has size below f(k)f(k) and serves as its own kernel.

∎

This proof is a bookkeeping trick: the kernel may have exponential size f(k)f(k). The interesting question is which problems admit small kernels. Vertex cover has two classical examples.

Buss’s rules

Buss and Goldsmith (1993) identified three rules to apply repeatedly:

  1. High degree. If vertex vv has degree greater than kk, vv belongs to every cover of size ≤k\le k; otherwise all its more than kk neighbors would be needed. Include vv, delete it and set k←k−1k \gets k - 1. If kk becomes negative, answer NO.
  2. Isolated vertices. An isolated vertex belongs to no minimum cover. Delete it.
  3. Too many edges. If neither preceding rule applies and more than k2k^2 edges remain, answer NO: each vertex covers at most kk edges, so kk vertices cover at most k2k^2.

An exercise proves each rule’s correctness and the size bound. Without isolated vertices, every vertex is either in the cover or neighbors one of its ≤k\le k vertices, each having at most ≤k\le k neighbors. More than k2+kk^2 + k remaining vertices therefore also imply NO. Combining the kernel with branching solves vertex cover in O(n+m+2kk2)\bigO(n + m + 2^k k^2): the exponential term no longer multiplies the original graph size.

InteractiveKernelize vertex cover
h1h2h3h4abcdexyzremaining k = 5
done
Bounded search tree over the kernel (depth ≤ 5)
·abcdxyexydxy
  • forced by degree > k
  • kernel
  • chosen by the search
  • branch that fails
  • solution
9
Remaining kk5
Live vertices8 of 55
Live edges8 of 48
Forced by rule 1h1, h2, h3, h4
Kernel bound: edges ≤k2\le k^28 ≤ 25? yes
Tree search nodes13 (maximum 63)
YES: a vertex cover of size 9, {h1, h2, h3, h4, a, b, d, x, y}.
A graph with 55 vertices and 48 edges: four hubs with 12, 11, 10, and 7 pendant leaves, a kernel formed by a pentagon and a triangle, and three isolated vertices. Does it have a vertex cover of size kk? Reproduce the kernelization step by step: each vertex with a degree greater than kk enters the cover (in orange) and kk decreases, with the threshold also decreasing; isolated vertices are removed; at the end, the k2k^2 edge bound is checked, and the search tree runs on the kernel (below), choosing an uncovered edge and testing its two ends. With k=9k = 9 the answer is YES. Lower to k=8k = 8: the kernel is the same, but the search tree runs out. Lower to k=6k = 6: the edge bound answers NO without searching. Increase to k=10k = 10 or 11: how many hubs are no longer forced?

Watch rule 1 cascade at k=9k = 9. The first three hubs have degrees 12, 11 and 10, all greater than 9, so they enter the cover and reduce the budget to 6. The fourth hub, degree 7, did not exceed the original threshold but exceeds the new one and enters too. All 40 leaves become isolated and disappear under rule 2. A pentagon and triangle remain: 8 vertices and 8 edges with k′=5k' = 5, far below k′2=25k'^2 = 25. The pentagon requires 3 vertices and the triangle 2, exactly the budget. Search visits 13 nodes: its first branch takes aa, bb, cc and dd, spending four vertices on the pentagon and leaving too little for the triangle; backtracking finds {a,b,d,x,y}\{a, b, d, x, y\}. With k=8k = 8, the kernel is identical but k′=4k' = 4, and search visits all 25−1=312^5 - 1 = 31 nodes before answering NO. With k=6k = 6, no search is needed: 8 edges remain and k′2=4k'^2 = 4.

A kernel of 2k vertices by linear programming

Buss’s kernel has O(k2)\bigO(k^2) vertices. The vertex-cover LP relaxation gives a linear-sized kernel:

min⁡∑v∈Vxvsubject toxu+xv≥1  ∀ uv∈E,0≤xv≤1.\min \sum_{v \in V} x_v \quad \text{subject to} \quad x_u + x_v \ge 1 \ \ \forall\, uv \in E, \qquad 0 \le x_v \le 1.
Proof

(a) Let xx be a polyhedron vertex, and define V+={v:0<xv<12}V^+ = \{v : 0 < x_v < \tfrac12\} and V−={v:12<xv<1}V^- = \{v : \tfrac12 < x_v < 1\}. Set y=x+ε(1V+−1V−)y = x + \eps(\ind_{V^+} - \ind_{V^-}) and z=x−ε(1V+−1V−)z = x - \eps(\ind_{V^+} - \ind_{V^-}). For small ε\eps, bounds 0≤⋅≤10 \le \cdot \le 1 remain satisfied. An edge with xu+xv>1x_u + x_v > 1 has slack. If xu+xv=1x_u + x_v = 1, either both coordinates equal 12\tfrac12 and remain unchanged, or they are 0 and 1 and remain unchanged, or one endpoint lies in V+V^+ and the other in V−V^-, canceling their changes. Thus yy and zz are feasible and x=(y+z)/2x = (y + z)/2. Since xx is a vertex, y=zy = z, giving V+=V−=∅V^+ = V^- = \emptyset.

(b) We accept part (b), whose proof uses an exchange argument on a matching between V0V_0 and V1V_1. For size, restricting xx to V1/2V_{1/2} is feasible for the relaxation on G[V1/2]G[V_{1/2}] and is optimal: a better solution combined with xx elsewhere would improve the original optimum and remain feasible. All neighbors of V0V_0 lie in V1V_1, since an endpoint assigned 0 forces the other to 1, and edges between V1/2V_{1/2} and V1V_1 are already covered. Hence ∣V1/2∣/2\abs{V_{1/2}}/2 lower-bounds the minimum cover of G[V1/2]G[V_{1/2}]. If that cover fits within k−∣V1∣k - \abs{V_1}, then ∣V1/2∣≤2(k−∣V1∣)\abs{V_{1/2}} \le 2(k - \abs{V_1}).

∎

In the figure’s graph, the LP optimum assigns 1 to all four hubs, 0 to leaves, and 12\tfrac12 to the kernel’s eight vertices. A pentagon needs 3 integral vertices but only 2.52.5 fractionally; a triangle needs 2 versus 1.51.5. Here the LP and Buss kernels coincide. A kernel with 2k2k vertices can have O(k2)\bigO(k^2) edges, essentially optimal in bit size: Dell and van Melkebeek (2010) proved that vertex cover has no kernel encodable in O(k2−ε)\bigO(k^{2-\eps}) bits unless coNP⊆NP/poly\mathrm{coNP} \subseteq \mathrm{NP/poly}. Related techniques show that some FPT problems, such as a path of length kk, admit no polynomial kernel under that assumption.

Treewidth as a parameter

Solution size is not the only useful parameter. In structured dynamic programming you saw tree decompositions and treewidth: a width-tt graph decomposes into bags of at most t+1t + 1 vertices arranged as a tree. Each bag separates what lies below it from what lies above. Here treewidth becomes the parameter.

A nice decomposition has four node types: leaves with empty bags; nodes introducing vertex vv, whose bag is the child’s bag plus vv; nodes forgetting it, whose bag is the child’s bag minus vv; and join nodes with two children having identical bags. Every width-tt decomposition becomes a nice decomposition of the same width with O(tn)\bigO(tn) nodes. For maximum independent set, let GνG_\nu be induced by vertices appearing in the subtree of ν\nu. For every independent S⊆XνS \subseteq X_\nu, let c[ν,S]c[\nu, S] be the size of the largest independent set II in GνG_\nu satisfying I∩Xν=SI \cap X_\nu = S. The transitions are:

  • Leaf: c[ν,∅]=0c[\nu, \emptyset] = 0.
  • Introduce vv: c[ν,S]=c[ν′,S∖{v}]+1c[\nu, S] = c[\nu', S \setminus \{v\}] + 1 if v∈Sv \in S and SS is independent; c[ν,S]=c[ν′,S]c[\nu, S] = c[\nu', S] if v∉Sv \notin S.
  • Forget vv: c[ν,S]=max⁡(c[ν′,S], c[ν′,S∪{v}])c[\nu, S] = \max\big(c[\nu', S],\ c[\nu', S \cup \{v\}]\big).
  • Join: c[ν,S]=c[ν1,S]+c[ν2,S]−∣S∣c[\nu, S] = c[\nu_1, S] + c[\nu_2, S] - \abs{S}.

Correctness follows from the separator property: Gν1G_{\nu_1} and Gν2G_{\nu_2} interact only through the shared bag, whose vertices SS have been counted twice at a join. Each table has 2t+12^{t+1} entries, giving cost O(2t tO(1) n)\bigO(2^t\, t^{\bigO(1)}\, n): FPT in width and linear in nn. Bodlaender (1996) proved that, for fixed tt, a width-tt decomposition can be found in linear time with constant 2O(t3)2^{\bigO(t^3)}. Courcelle’s theorem generalizes this dynamic programming to properties expressible in monadic second-order logic. The same separator argument connects two other modules: tree decompositions of CSPs and variable elimination in graphical models have costs exponential in width.

Is 2t2^t the right base? Lokshtanov, Marx and Saurabh (2011) proved that, under the hypothesis introduced next, independent set cannot be solved in O∗((2−ε)t)\bigO^*((2 - \eps)^t) for any ε>0\eps > 0. The textbook dynamic program is therefore probably optimal even in its base.

ETH and SETH: conditional lower bounds

P ≠\neq NP excludes polynomial-time 3-SAT, but is compatible with O(2n)\bigO(2^{\sqrt n}) or O(nlog⁡n)\bigO(n^{\log n}) algorithms. Ruling these out requires a quantitative hypothesis. Define

sk=inf⁡{δ≥0:k-SAT with n variables is solvable in O(2δn)}.s_k = \inf\{\delta \ge 0 : \text{$k$-SAT with $n$ variables is solvable in } \bigO(2^{\delta n})\}.

This is a nondecreasing sequence with s2=0s_2 = 0, because 2-SAT is linear, and sk≤1s_k \le 1 by brute force.

SETH implies ETH, and both imply P ≠\neq NP. Neither is proved. Their support comes from decades of kk-SAT algorithms whose exponent improvements vanish as Θ(1/k)\Theta(1/k), and a coherent theory of consequences. ETH becomes useful through the sparsification lemma (Impagliazzo, Paturi and Zane, 2001), allowing m=O(n)m = \bigO(n) clauses without losing the bound. It implies that ETH excludes 2o(n+m)2^{o(n + m)}-time 3-SAT.

Proof

(1) Classical reductions from 3-SAT, including SAT to 3-SAT and catalog reductions such as 3-coloring, produce graphs with O(n+m)\bigO(n + m) vertices and edges from formulas with nn variables and mm clauses. A 2o(N)2^{o(N)} algorithm on the resulting graph, with N=O(n+m)N = \bigO(n + m), would solve 3-SAT in 2o(n+m)2^{o(n + m)}, contradicting sparsified ETH. (2) Since k≤nk \le n, a 2o(k)nO(1)2^{o(k)} n^{\bigO(1)} algorithm would be 2o(n)2^{o(n)}, contradicting (1). (3) This needs a finer reduction grouping variables into kk blocks, which we omit.

∎

Notice what (2) says: the O(ck)\bigO(c^k) search tree cannot become subexponential in kk, so only the base can improve. Statement (1) also has a surprising positive interpretation. On planar graphs, many of these problems admit 2O(n)2^{\bigO(\sqrt n)} algorithms, because the planar separator theorem gives treewidth O(n)\bigO(\sqrt n). Reductions from 3-SAT to planar graphs are quadratic-sized, so ETH excludes 2o(n)2^{o(\sqrt n)}: the square root is exactly the right dependence.

SETH gives finer lower bounds with exact bases: CNF-SAT has no O∗((2−ε)n)\bigO^*((2 - \eps)^n) algorithm, by definition; independent set has no O∗((2−ε)t)\bigO^*((2 - \eps)^{t}) algorithm parameterized by treewidth tt; and, most strikingly, it yields lower bounds for polynomial-time problems.

Fine-grained complexity

Edit distance has been computable in O(n2)\bigO(n^2) since Wagner and Fischer (1974), with only logarithmic-factor improvements in half a century. All-pairs shortest paths, APSP, take O(n3)\bigO(n^3), and the best known improvement is smaller than every fixed power of nn. Finding three numbers summing to zero among nn inputs, 3SUM, takes O(n2)\bigO(n^2) by sorting and using two pointers, with similar stagnation. NP-completeness says nothing here: all are in P. The question is why their exponents are 2 or 3 rather than 1.91.9 or 2.92.9.

The bridge from SAT to polynomial-time problems looks innocent.

Proof

Let φ\varphi be a CNF formula with variables x1,…,xnx_1, \dots, x_n, assuming even nn for simplicity, and clauses C1,…,CmC_1, \dots, C_m. Split the variables into X1={x1,…,xn/2}X_1 = \{x_1, \dots, x_{n/2}\} and the remaining X2X_2. For each of the 2n/22^{n/2} assignments α\alpha to X1X_1, define aα∈{0,1}m\vb{a}_\alpha \in \{0,1\}^m by

(aα)j={0if α satisfies some literal of Cj,1otherwise,(\vb{a}_\alpha)_j = \begin{cases} 0 & \text{if } \alpha \text{ satisfies some literal of } C_j, \\ 1 & \text{otherwise,} \end{cases}

and similarly define bβ\vb{b}_\beta for every assignment β\beta to X2X_2. Then aα⊤bβ=0\vb{a}_\alpha\T\vb{b}_\beta = 0 exactly when every clause CjC_j has a literal satisfied by α\alpha or β\beta in CjC_j: equivalently, the full assignment (α,β)(\alpha, \beta) satisfies φ\varphi. Building the vectors costs O(2n/2 m n)\bigO(2^{n/2}\,m\,n). Taking N=2n/2N = 2^{n/2} and d=md = m, the hypothetical algorithm takes O(2(n/2)(2−ε)poly⁡(m))=O(2(1−ε/2)npoly⁡(m))\bigO(2^{(n/2)(2 - \eps)}\operatorname{poly}(m)) = \bigO(2^{(1 - \eps/2)n}\operatorname{poly}(m)). For kk-SAT with fixed kk, m≤(2n)km \le (2n)^k, so poly⁡(m)\operatorname{poly}(m) is polynomial in nn and kk-SAT would run in O(2(1−ε/2)n nO(1))\bigO(2^{(1-\eps/2)n}\,n^{\bigO(1)}) for every kk, contradicting SETH.

∎

This is meet-in-the-middle: enumerate assignments to both halves separately, then combine through an orthogonal pair. Sparsification additionally lets us assume m=O(n)m = \bigO(n), hence d=O(log⁡N)d = \bigO(\log N), the OV-conjecture regime. From OV, hardness propagates to string and graph problems.

The reduction turns two vector lists into two strings of length Npoly⁡(d)N\operatorname{poly}(d). Each coordinate becomes a small string gadget whose alignment costs slightly less when at least one of the corresponding coordinates of a\vb{a} and b\vb{b} is 0. A vector concatenates its coordinate gadgets; final strings interleave vectors with padding forcing every inexpensive alignment to pair complete vectors across lists. Total edit distance falls below a computable threshold exactly when an orthogonal pair exists. A O(n2−δ)\bigO(n^{2-\delta}) edit-distance algorithm would solve OV in O(N2−δpoly⁡(d))\bigO(N^{2-\delta}\operatorname{poly}(d)) and, by the preceding theorem, CNF-SAT in O(2(1−δ/2)npoly⁡(m))\bigO(2^{(1-\delta/2)n}\operatorname{poly}(m)). Lesson 15’s quadratic dynamic program is therefore essentially optimal unless SETH fails. Similar results hold for longest common subsequence, Fréchet distance between curves and diameter approximation in sparse graphs.

InteractiveThe network of fine-grained reductions
SETH family3SUM familyAPSP familyCNF-SATOrthogonal vectorsEdit distanceLCSDiameter3SUMCollinear pointsZero-weight triangleAPSPProduct (min, +)Negative triangle
  • A → B: a fast algorithm for B gives one for A
  • made faster by the selected problem
Edit distance
Edit distance between two strings of length nn: the Wagner-Fischer dynamic program is quadratic and since Masek and Paterson (1980) only logarithmic factors have been gained. Backurs and Indyk (2015) explained why.
Best known algorithm
O(n2)\bigO(n^2) except for logarithmic factors
Conditional lower bound
n2−o(1)n^{2-o(1)} under SETH
Other problems made faster2
A substantially faster algorithm for this problem would refute SETH.
Eleven problems, in three families according to the conjecture from which they inherit their difficulty. An arrow A→BA \to B is a fine-grained reduction: a substantially faster algorithm for BB would give one for AA. Click a problem: it illuminates all that would fall with it and the panel says which conjecture would be refuted. Click an arrow to read the idea of the reduction. Compare the edit distance with the zero-weight triangle, which is at the intersection of two families, and notice the equivalences of the APSP family, which work in both directions.

Three observations about this network:

  • There are families, rather than one hierarchy. No fine-grained reduction is known in either direction between SETH, 3SUM and APSP. Carmosino and colleagues (2016) proved that, under nondeterministic SETH, NSETH, 3SUM and APSP cannot be SETH-hard through deterministic fine-grained reductions. They are three independent conjectures; zero-weight triangle is interesting precisely because it inherits two of them.
  • The APSP family contains equivalences. Vassilevska Williams and Williams (2010) proved that APSP, min-plus matrix multiplication, negative-weight triangle and several other problems are subcubically equivalent: either all have O(n3−ε)\bigO(n^{3-\eps}) algorithms or none does. Detecting one negative triangle seems easier than computing n2n^2 distances, but is not.
  • The chain back to SAT is short. A O(n1.9)\bigO(n^{1.9}) edit-distance algorithm would yield O(N1.9poly⁡(d))\bigO(N^{1.9}\operatorname{poly}(d)) for OV and then O(20.95npoly⁡(m))\bigO(2^{0.95n}\operatorname{poly}(m)) for CNF-SAT, an improvement the SAT community has not achieved in decades.

Lab: exact algorithms from scratch

The following cells implement the lesson’s techniques in pure Python, using NumPy for large enumerations. Each browser cell runs in a few seconds. Instead of asking how large an instance can be solved in one minute, we measure work growth and extrapolate.

First, knapsack branch and bound with both bounds, compared against capacity-based dynamic programming. Sort by density, explore taking the item first, and prune using ⌊fˉ⌋≤z∗\lfloor \bar f \rfloor \le z^*.

[ ]Branch and bound for the knapsackBrowser
import random

def mochila_instancia(n, semilla, iguales=False):
    rnd = random.Random(semilla)
    if iguales:                                  # v = w, pesos pares y capacidad impar
        w = [2 * rnd.randint(10**4, 10**5) for _ in range(n)]
        return w, w[:], (sum(w) // 2) | 1
    w = [rnd.randint(10, 40) for _ in range(n)]
    v = [wi + rnd.randint(-3, 10) for wi in w]
    return w, v, sum(w) // 2

def mochila_dp(w, v, C):
    f = [0] * (C + 1)
    for wi, vi in zip(w, v):
        for c in range(C, wi - 1, -1):
            if f[c - wi] + vi > f[c]:
                f[c] = f[c - wi] + vi
    return f[C]

def mochila_bb(w, v, C, cota="fraccionaria"):
    """Ramificación y poda en profundidad. Devuelve (óptimo, nodos visitados)."""
    n = len(w)
    orden = sorted(range(n), key=lambda i: -v[i] / w[i])      # por densidad
    w = [w[i] for i in orden]
    v = [v[i] for i in orden]
    suf = [0] * (n + 1)
    for i in range(n - 1, -1, -1):
        suf[i] = suf[i + 1] + v[i]
    mejor, nodos = 0, 0

    def cota_de(d, valor, cap):
        if cota == "trivial":
            return valor + suf[d]
        b = valor                    # relajación lineal: voraz por densidad, el último partido
        for i in range(d, n):
            if w[i] <= cap:
                b += v[i]
                cap -= w[i]
            else:
                return b + v[i] * cap / w[i]
        return b

    def visitar(d, valor, cap):
        nonlocal mejor, nodos
        nodos += 1
        if cap < 0 or int(cota_de(d, valor, cap)) <= mejor:
            return
        if d == n:
            mejor = valor
            return
        visitar(d + 1, valor + v[d], cap - w[d])             # tomar primero
        visitar(d + 1, valor, cap)                           # dejar

    visitar(0, 0, C)
    return mejor, nodos

print(" n   óptimo   nodos (trivial)   nodos (fraccionaria)          2^(n+1) - 1")
for n in [10, 13, 16, 19, 30, 45, 60]:
    w, v, C = mochila_instancia(n, n)
    opt = mochila_dp(w, v, C)
    triv = mochila_bb(w, v, C, "trivial")[1] if n <= 19 else "·"
    valor, nodos = mochila_bb(w, v, C)
    assert valor == opt
    print(f"{n:2d}  {opt:6d}   {triv:>15}   {nodos:>20}   {2**(n + 1) - 1:>18}")

print("\nla misma cota fraccionaria con todas las densidades iguales:")
for n in [12, 14, 16, 18]:
    w, v, C = mochila_instancia(n, n, iguales=True)
    valor, nodos = mochila_bb(w, v, C)
    print(f"n = {n}:  óptimo {valor} (capacidad {C}),  nodos {nodos:>7}  de {2**(n + 1) - 1:>7}  ({nodos / 2**(n + 1):.0%})")

With distinct item densities, the fractional bound proves a 60-item optimum while visiting fewer than two hundred nodes of a 2.3×10182.3\times 10^{18}-node tree; the trivial bound already needs almost a hundred thousand nodes for 19 items. Equal densities change the story. Whenever remaining items cannot all fit, the relaxation fills capacity and has value exactly CC. Since CC is odd and every sum is even, the incumbent never exceeds C−1C - 1 and this bound never prunes those nodes. Pruning begins only when remaining items cannot fill capacity. The visited tree occupies between a fifth and half of 2n+12^{n+1} nodes, showing clean exponential growth: a measured version of the earlier warning.

Next, meet-in-the-middle. todas_las_sumas generates the 2m2^m sums of mm numbers by doubling with NumPy. Brute force generates them for all nn numbers; the faster version handles each half, joins through searchsorted and reconstructs indices from list positions. Bit kk of a position indicates whether number kk of that half was taken.

[ ]Meet-in-the-middle for subset sumBrowser
import random
import time
import numpy as np

def todas_las_sumas(a):
    """Las 2^len(a) sumas de subconjuntos; la posición i corresponde al subconjunto con los bits de i."""
    s = np.zeros(1, dtype=np.int64)
    for x in a:
        s = np.concatenate([s, s + x])
    return s

def suma_fuerza_bruta(a, T):
    return bool(np.any(todas_las_sumas(a) == T))

def suma_mitm(a, T):
    """Índices de un subconjunto de a que suma T, o None."""
    h = len(a) // 2
    izq, der = todas_las_sumas(a[:h]), todas_las_sumas(a[h:])
    orden = np.argsort(der, kind="stable")
    der_ord = der[orden]
    faltan = T - izq
    pos = np.minimum(np.searchsorted(der_ord, faltan), len(der_ord) - 1)
    hay = np.nonzero(der_ord[pos] == faltan)[0]
    if len(hay) == 0:
        return None
    i = int(hay[0])
    j = int(orden[pos[i]])
    return [k for k in range(h) if i >> k & 1] + [h + k for k in range(len(a) - h) if j >> k & 1]

rnd = random.Random(0)
print(" n   fuerza bruta 2^n (s)   meet-in-the-middle (s)   memoria de una mitad")
for n in [16, 18, 20, 22, 28, 34, 40]:
    a = [rnd.randint(1, 10**12) for _ in range(n)]
    T = sum(a[i] for i in rnd.sample(range(n), n // 3))
    tb = "·"
    if n <= 22:
        t0 = time.perf_counter()
        assert suma_fuerza_bruta(a, T)
        tb = f"{time.perf_counter() - t0:.3f}"
    t0 = time.perf_counter()
    sol = suma_mitm(a, T)
    tm = time.perf_counter() - t0
    assert sol is not None and sum(a[i] for i in sol) == T
    print(f"{n:2d}   {tb:>20}   {tm:>22.3f}   {8 * 2**(n - n // 2) / 2**20:>14.3f} MiB")

Each extra number theoretically doubles brute-force work but multiplies meet-in-the-middle work by 2\sqrt 2. Measured times broadly follow this, with sorting and memory accesses also mattering for large lists. The faster method solves n=40n = 40 in a fraction of a second. Extrapolating brute force to n=40n = 40 gives hours, and this vectorized implementation would additionally need 8 TiB to store 2402^{40} sums. Watch the final column: at n=40n = 40 each half takes 8 MiB; at n=60n = 60, 8 GiB per half. Memory becomes limiting before time.

The three-rule independent-set algorithm, checked against brute force on a small graph and measured on random graphs of mean degree 4:

[ ]Independent set by branchingBrowser
import random

def mis_ramificando(adj):
    """Tamaño del conjunto independiente máximo y nodos del árbol de búsqueda."""
    nodos = 0

    def rec(vivos):
        nonlocal nodos
        nodos += 1
        if not vivos:
            return 0
        grado = {u: len(adj[u] & vivos) for u in vivos}
        u = min(vivos, key=grado.get)
        if grado[u] <= 1:                            # regla 1: tomar u es seguro
            return 1 + rec(vivos - adj[u] - {u})
        v = max(vivos, key=grado.get)
        if grado[v] >= 3:                            # regla 3: ramificar (n - 1, n - 4)
            return max(rec(vivos - {v}), 1 + rec(vivos - adj[v] - {v}))
        total, vistos = 0, set()                     # regla 2: todo grado 2, unión de ciclos
        for s in vivos:
            if s in vistos:
                continue
            pila, comp = [s], {s}
            while pila:
                x = pila.pop()
                for y in adj[x] & vivos:
                    if y not in comp:
                        comp.add(y)
                        pila.append(y)
            vistos |= comp
            total += len(comp) // 2
        return total

    return rec(frozenset(adj)), nodos

def grafo_aleatorio(n, grado_medio, semilla):
    rnd = random.Random(semilla)
    adj = {i: set() for i in range(n)}
    aristas = 0
    while aristas < n * grado_medio // 2:
        u, v = rnd.randrange(n), rnd.randrange(n)
        if u != v and v not in adj[u]:
            adj[u].add(v)
            adj[v].add(u)
            aristas += 1
    return {u: frozenset(s) for u, s in adj.items()}

def mis_fuerza_bruta(adj):
    n, mejor = len(adj), 0
    for S in range(1 << n):
        if all(not (S >> v & 1) for u in range(n) if S >> u & 1 for v in adj[u]):
            mejor = max(mejor, bin(S).count("1"))
    return mejor

for semilla in range(3):
    g = grafo_aleatorio(13, 3, semilla)
    assert mis_ramificando(g)[0] == mis_fuerza_bruta(g)
print("coincide con la fuerza bruta en tres grafos de 13 vértices")

print("\n n   α(G)   nodos del árbol   cota 1.3803^n")
for n in [20, 30, 40, 50, 60]:
    a, nodos = mis_ramificando(grafo_aleatorio(n, 4, n))
    print(f"{n:2d}   {a:4d}   {nodos:15d}   {1.3803**n:13.3g}")

Now parameterized vertex cover: Buss’s rules, search on the kernel and, for comparison, the LP kernel. Instances have known optimum k∗k^* by construction, combining hubs with many leaves, triangles, pentagons and isolated vertices. Measure search with k=k∗k = k^*, a YES instance, and k=k∗−1k = k^* - 1, a NO instance requiring the expensive exhaustion of every branch.

[ ]Vertex cover: Buss kernel, search tree and linear kernelBrowser
import random
import time
import numpy as np
from scipy.optimize import linprog

def instancia_vc(hubs, triangulos, pentagonos, semilla):
    rnd = random.Random(semilla)
    aristas, n = [], 0
    def nuevo():
        nonlocal n
        n += 1
        return n - 1
    for _ in range(hubs):
        h = nuevo()
        for _ in range(rnd.randint(30, 60)):
            aristas.append((h, nuevo()))
    for _ in range(triangulos):
        a, b, c = nuevo(), nuevo(), nuevo()
        aristas += [(a, b), (b, c), (c, a)]
    for _ in range(pentagonos):
        p = [nuevo() for _ in range(5)]
        aristas += [(p[i], p[(i + 1) % 5]) for i in range(5)]
    n += 50                                           # vértices aislados
    rnd.shuffle(aristas)
    return n, aristas, hubs + 2 * triangulos + 3 * pentagonos

def kernel_buss(aristas, k):
    """(forzados, aristas del núcleo, k restante), o None si la respuesta es NO."""
    vivas, forzados = set(aristas), []
    while True:
        grado = {}
        for u, v in vivas:
            grado[u] = grado.get(u, 0) + 1
            grado[v] = grado.get(v, 0) + 1
        altos = [u for u, g in grado.items() if g > k]
        if not altos:
            break
        u = max(altos, key=grado.get)                 # regla 1
        forzados.append(u)
        vivas = {e for e in vivas if u not in e}
        k -= 1
        if k < 0:
            return None
    if len(vivas) > k * k:                            # regla 3 (la 2 es implícita: solo hay aristas)
        return None
    return forzados, sorted(vivas), k

def vc_arbol(aristas, k):
    """Árbol de búsqueda acotado: (recubrimiento o None, nodos visitados)."""
    nodos = 0
    def rec(elegidos, k):
        nonlocal nodos
        nodos += 1
        e = next(((u, v) for u, v in aristas if u not in elegidos and v not in elegidos), None)
        if e is None:
            return set(elegidos)
        if k == 0:
            return None
        for x in e:                                   # u o v está en todo recubrimiento
            elegidos.add(x)
            r = rec(elegidos, k - 1)
            elegidos.discard(x)
            if r is not None:
                return r
        return None
    return rec(set(), k), nodos

def vc_fpt(aristas, k):
    ker = kernel_buss(aristas, k)
    if ker is None:
        return None, 0, 0
    forzados, nucleo, kk = ker
    sol, nodos = vc_arbol(nucleo, kk)
    return (None if sol is None else set(forzados) | sol), nodos, len(nucleo)

print(" k*     n     m   aristas núcleo   nodos (k = k*)   nodos (k = k* - 1)   tiempo (s)")
for hubs, tri, pen in [(4, 1, 1), (5, 2, 1), (6, 2, 2), (6, 3, 2), (8, 3, 3)]:
    n, A, opt = instancia_vc(hubs, tri, pen, hubs)
    t0 = time.perf_counter()
    sol, nodos_si, mk = vc_fpt(A, opt)
    assert sol is not None and len(sol) <= opt and all(u in sol or v in sol for u, v in A)
    sol_no, nodos_no, _ = vc_fpt(A, opt - 1)
    assert sol_no is None
    print(f"{opt:3d} {n:5d} {len(A):5d}   {mk:14d}   {nodos_si:14d}   {nodos_no:18d}   {time.perf_counter() - t0:10.3f}")

# núcleo de Nemhauser-Trotter: un vértice óptimo de la relajación lineal (símplex dual)
n, A, opt = instancia_vc(6, 3, 2, 6)
M = np.zeros((len(A), n))
for i, (u, v) in enumerate(A):
    M[i, u] = M[i, v] = -1
r = linprog(np.ones(n), A_ub=M, b_ub=-np.ones(len(A)), bounds=(0, 1), method="highs-ds")
x = r.x
print(f"\nrelajación lineal: valor {r.fun:.1f} frente al óptimo entero {opt}")
print("¿semientera?", bool(np.allclose(2 * x, np.round(2 * x))))
V1, Vm, V0 = int(np.isclose(x, 1).sum()), int(np.isclose(x, 0.5).sum()), int(np.isclose(x, 0).sum())
print(f"V1 = {V1} (concentradores), V1/2 = {Vm} (núcleo), V0 = {V0}")
print(f"núcleo lineal: {Vm} vértices <= 2(k* - |V1|) = {2 * (opt - V1)}")

In all five instances, Buss’s kernel contains exactly the triangle and pentagon edges: rule 1 selects hubs and their leaves disappear. Search with k=k∗k = k^* finds a solution with little backtracking, between 7 and 159 nodes. With k=k∗−1k = k^* - 1, it visits 2k′+1−12^{k'+1} - 1 nodes, where k′=k∗−1−(hubs)k' = k^* - 1 - (\text{hubs}): the theorem’s exact worst case, because every branch spends budget without covering everything. The final row has 32 76732\,767 nodes with k′=14k' = 14; each extra budget unit would double the tree regardless of original graph size. As predicted, the LP kernel is half-integral: 6 hubs receive 1, leaves 0, and the 19 triangle and pentagon vertices 12\tfrac12. This is below 2(k∗−∣V1∣)=242(k^* - \abs{V_1}) = 24 because each triangle needs 2 integral vertices but only 1.51.5 fractionally, and each pentagon 3 versus 2.52.5.

The final cell checks Williams’s reduction: random 3-CNF formulas with 12 variables, near the satisfiability threshold, become two lists of 26=642^6 = 64 vectors. Matrix multiplication detects orthogonal pairs.

[ ]From CNF-SAT to orthogonal vectorsBrowser
import random
import numpy as np

def cnf_aleatoria(n, m, k, rnd):
    """Literales como enteros con signo: +i es x_i, -i es su negación (i desde 1)."""
    return [[(v + 1) * rnd.choice([1, -1]) for v in rnd.sample(range(n), k)] for _ in range(m)]

def satisfacible(n, F):
    return any(all(any((x >> (abs(l) - 1) & 1) == (l > 0) for l in c) for c in F) for x in range(1 << n))

def vectores(F, variables):
    """Una fila por asignación de 'variables'; columna j a 0 si esa asignación satisface la cláusula j."""
    V = np.ones((1 << len(variables), len(F)), dtype=np.int64)
    for x in range(1 << len(variables)):
        valor = {var: (x >> i) & 1 for i, var in enumerate(variables)}
        for j, c in enumerate(F):
            if any(abs(l) - 1 in valor and valor[abs(l) - 1] == (l > 0) for l in c):
                V[x, j] = 0
    return V

rnd = random.Random(3)
n, coinciden, sat = 12, 0, 0
for prueba in range(30):
    F = cnf_aleatoria(n, rnd.choice([40, 50, 55, 60]), 3, rnd)
    A = vectores(F, list(range(n // 2)))
    B = vectores(F, list(range(n // 2, n)))
    hay_ortogonal = bool(np.any(A @ B.T == 0))
    coinciden += hay_ortogonal == satisfacible(n, F)
    sat += hay_ortogonal
print(f"{coinciden}/30 fórmulas: par ortogonal <=> satisfacible   ({sat} satisfacibles)")
print(f"tamaño de la instancia OV: N = 2^{n // 2} = {2 ** (n // 2)} vectores por lista, d = m cláusulas")

The professional version: an industrial solver

An integer-programming solver applies our knapsack branch-and-bound idea with stronger bounds, cuts and heuristics. SciPy includes one: scipy.optimize.milp calls HiGHS, an industrial-quality open-source solver. The cell compares a large random knapsack, easy for every method; the hard equal-density family and meet-in-the-middle on that family; and vertex cover on the lab instance.

[ ]HiGHS versus our own algorithmsBrowser
import random
import time
import numpy as np
from scipy.optimize import milp, LinearConstraint, Bounds

def mochila_milp(w, v, C, exacto=True):
    w, v = np.asarray(w, float), np.asarray(v, float)
    opciones = {"mip_rel_gap": 0} if exacto else {}                 # 0: exige demostrar el óptimo
    r = milp(-v, constraints=LinearConstraint(w[None, :], -np.inf, C), integrality=np.ones(len(w)),
             bounds=Bounds(0, 1), options=opciones)
    return round(-r.fun), r.mip_node_count

# 1) mochila aleatoria con 1000 objetos: la relajación es casi exacta
rnd = random.Random(1)
w = [rnd.randint(10, 40) for _ in range(1000)]
v = [wi + rnd.randint(-3, 10) for wi in w]
t0 = time.perf_counter()
print("1000 objetos:", mochila_milp(w, v, sum(w) // 2), f"{time.perf_counter() - t0:.2f} s  (óptimo, nodos)")

# 2) densidades iguales: la cota lineal no informa y los nodos se disparan
for n in [12, 14, 16]:
    rnd = random.Random(n)
    w = [2 * rnd.randint(10**4, 10**5) for _ in range(n)]
    C = (sum(w) // 2) | 1
    t0 = time.perf_counter()
    val, nodos = mochila_milp(w, w, C)
    t1 = time.perf_counter() - t0
    # el mismo problema por meet-in-the-middle: la mejor suma <= C cruzando dos listas ordenadas
    h = n // 2
    L = np.array([sum(w[i] for i in range(h) if S >> i & 1) for S in range(1 << h)])
    R = np.sort([sum(w[h + i] for i in range(n - h) if S >> i & 1) for S in range(1 << (n - h))])
    t0 = time.perf_counter()
    j = np.searchsorted(R, C - L, side="right") - 1
    mejor = int(np.max(np.where(j >= 0, L + R[np.maximum(j, 0)], -1)))
    t2 = time.perf_counter() - t0
    print(f"iguales, n = {n}: HiGHS {val} en {t1:.2f} s y {nodos} nodos;  meet-in-the-middle {mejor} en {t2:.4f} s")
    val_def, nodos_def = mochila_milp(w, w, C, exacto=False)
    print(f"      con el hueco por defecto: {val_def} en {nodos_def} nodos  ({'óptimo' if val_def == val else f'le faltan {val - val_def}'})")

# 3) vertex cover como programa entero, sobre una instancia del laboratorio
n, A, opt = instancia_vc(8, 3, 3, 8)
M = np.zeros((len(A), n))
for i, (u, v2) in enumerate(A):
    M[i, u] = M[i, v2] = 1
t0 = time.perf_counter()
r = milp(np.ones(n), constraints=LinearConstraint(M, 1, np.inf), integrality=np.ones(n), bounds=Bounds(0, 1))
print(f"vertex cover: HiGHS {round(r.fun)} (óptimo {opt}) en {time.perf_counter() - t0:.2f} s y {r.mip_node_count} nodos")

Three readings matter. On the large random knapsack, HiGHS proves optimality at the root without branching: the LP value 16 179.2216\,179.22 has integer part equal to optimum 16 17916\,179, so the bound certifies any primal-heuristic solution of that value. On equal densities, the industrial solver suffers like our fractional bound, visiting thousands of nodes for 16 items, whereas the structure-specific meet-in-the-middle algorithm joins its lists in under a millisecond. For vertex cover, the LP value is 20, assigning 12\tfrac12 to triangle and pentagon vertices, versus integral optimum 23. HiGHS presolve and cuts close that gap at the root. Finally, inspect the default-gap rows. Without mip_rel_gap = 0, HiGHS stops once the relative incumbent-bound gap falls below 10−410^{-4}. This is not an optimality proof: at n=16n = 16 it reports successful termination after 232 nodes with 870 454870\,454, six units below optimum. Equal-density instances have tiny relative gaps almost immediately, exactly where default tolerance can mislead.

Outside the browser, OR-Tools CP-SAT is a de facto standard for combinatorial problems. It combines constraint propagation, CDCL-style clause learning, linear relaxations and parallel search. Vertex cover can be written as follows; this example does not run here because OR-Tools is unavailable in the browser:

from ortools.sat.python import cp_model

def vertex_cover_cpsat(n, aristas, segundos=10):
    m = cp_model.CpModel()
    x = [m.NewBoolVar(f"x{v}") for v in range(n)]
    for u, v in aristas:
        m.AddBoolOr([x[u], x[v]])          # cada arista tiene un extremo elegido
    m.Minimize(sum(x))
    s = cp_model.CpSolver()
    s.parameters.max_time_in_seconds = segundos
    s.parameters.num_workers = 8           # búsqueda en cartera, en paralelo
    estado = s.Solve(m)
    return s.StatusName(estado), int(s.ObjectiveValue()), s.BestObjectiveBound()

StatusName distinguishes OPTIMAL, proved optimality, from FEASIBLE, a solution found without closing the bound gap. BestObjectiveBound reports the proven search bound, the same incumbent-bound pair used by branch and bound.

Typical errors

Exercises

NumericFPT versus XP
With k=20k = 20 and n=106n = 10^6, how many orders of magnitude separate nkn^k from 2kn2^k n? Give log⁡10(nk/(2kn))\log_{10}(n^k / (2^k n)).
NumericThe base of degree-based branching
If a vertex vv has degree at least 3, the vertex-cover algorithm branches into «vv enters» (k−1k - 1) or «its neighbors enter» (k−3k - 3 or less). What is the base α\alpha of the running time O∗(αk)\bigO^*(\alpha^k)? Give three decimals.
NumericMeet-in-the-middle memory requirements
For a subset sum with n=60n = 60 numbers, the sums of one half are stored as 8-byte integers in a NumPy array. How many GiB does that list occupy? (1 GiB=2301\ \text{GiB} = 2^{30} bytes.)
NumericThe attack on double encryption
A cipher with 56-bit keys is applied twice with independent keys. The meet-in-the-middle attack encrypts a known message with all keys k1k_1 and decrypts the corresponding ciphertext with all keys k2k_2. How many encryption or decryption operations does it make in total, as a power of 2? Give the exponent.
QuizFPT or not?
Which of these parameterized problems are known to be FPT?

More than one answer may be correct.

QuizEdit distance in n^1.9 time
Suppose that someone publishes a correct algorithm that computes the edit distance of two strings of length nn in O(n1.9)\bigO(n^{1.9}). According to the reduction by Backurs and Indyk, what follows?

More than one answer may be correct.

QuizRead a conditional bound
A colleague writes in a report: 'It has been proven that independent set on graphs of treewidth tt requires time 2t2^t'. What is the appropriate correction?
ProofVertex cover in time O(2^k (n + m))
Prove: Vertex cover parametrized by kk is decided in time O(2k(n+m))\bigO(2^k(n + m)).
0
Consider the VC(G,k)(G, k) algorithm: if GG has no edges, answer YES; if k=0k = 0, answer NO; otherwise, take an edge uvuv and answer YES if VC(G−u,k−1)(G - u, k - 1) or VC(G−v,k−1)(G - v, k - 1) answers YES.

Step 1 of 4. Why is it correct to branch only with uu and with vv?

ProofBuss's rules produce a kernel with k² edges
Prove: After applying Buss's rules as long as possible, either the answer is NO or there remains an equivalent instance (G′,k′)(G', k') with k′≤kk' \le k, at most k′2k'^2 edges and at most k′2+k′k'^2 + k' vertices.
0
Rule 1: if deg⁡(v)>k\deg(v) > k, add vv to the solution, remove vv and do k←k−1k \gets k - 1. Rule 2: remove isolated vertices. Rule 3: if none apply and there are more than k2k^2 edges, respond NO. If at any point k<0k < 0, respond NO.

Step 1 of 4. Why does rule 1 preserve the answer?

CodeMeet-in-the-middle with n = 40
Implement suma_subconjunto(a, T): given a list a of up to 40 positive integers (of up to 101210^{12}) and a target T, return a list of distinct indices whose elements sum exactly to T, or None if it does not exist. It should take less than 3 seconds with n=40n = 40 in the browser, so enumeration of 2402^{40} subsets is ruled out: use meet-in-the-middle. You can use NumPy (for example, np.concatenate, np.argsort and np.searchsorted). The empty subset sums 0.
import numpy as np

def suma_subconjunto(a, T):
  """Índices de un subconjunto de a con suma T, o None."""
  # 1) parte a en dos mitades y genera las 2^(n/2) sumas de cada una
  # 2) ordena las de la derecha y busca T - s para cada suma s de la izquierda
  # 3) reconstruye los índices a partir de las posiciones (bits) de las dos sumas
  return None
Shift+Enter to run

Summary

Key idea
NP-hardness describes worst-case complexity, not everyday behavior: relaxation bounds prune search, meet-in-the-middle halves the exponent, parameterized complexity confines the explosion to a small parameter, and kernelization reduces the instance to size g(k)g(k). When these are insufficient, ETH and SETH identify the conjecture an improvement would refute, even for polynomial-time problems such as edit distance.
  • Branch and bound: prune every node whose optimistic bound cannot improve the incumbent. The knapsack LP is density-greedy with one fractional item. Replacing the trivial bound with the fractional bound saves orders of magnitude; equal densities defeat it and restore exponential search.
  • Meet-in-the-middle: subset sum falls from 2n2^n to O(2n/2 n)\bigO(2^{n/2}\,n) by enumerating and joining two halves, using 2n/22^{n/2} memory. The same idea breaks double encryption.
  • Exact algorithms: branching recurrences yield bases such as 1.38031.3803 for independent set. Measure and conquer improves the analysis by changing the measure.
  • FPT and kernels: vertex cover admits O(2k(n+m))\bigO(2^k(n + m)) search and kernels with k2k^2 edges by Buss’s rules or 2k2k vertices through half-integral LP. FPT is equivalent to kernelizability. Independent set is W[1]-hard by solution size but FPT by treewidth, using O(2ttO(1)n)\bigO(2^t t^{\bigO(1)} n) dynamic programming.
  • ETH and SETH: conditional lower bounds exclude 2o(n)2^{o(n)} for classical NP-complete problems, 2o(k)2^{o(k)} for vertex cover and f(k) no(k)f(k)\,n^{o(k)} for clique, with exact-base bounds under SETH.
  • Fine-grained complexity: SETH implies the OV conjecture through meet-in-the-middle on assignments; OV reduces to edit distance, LCS and diameter problems, whose quadratic algorithms are optimal unless SETH fails. 3SUM and APSP organize two further families, with no known reductions between them.