P, NP & NP-Completeness
Easy to check, maybe hard to find: the biggest open question in computer science.
Checking a filled-in sudoku takes a minute; filling one in can take an evening. Whether every problem whose solutions are easy to check is also easy to solve is the P versus NP question. It has been open since 1971, it carries a million-dollar prize, and it is the reason thousands of everyday problems have no known fast algorithm.
What you’ll learn
- Define decision problems, the classes P and NP through certificates and polynomial-time verifiers, and co-NP, and place them in .
- Define polynomial-time reductions, NP-hardness and NP-completeness, and explain why one NP-complete problem in P would put all of NP in P.
- Prove that 3-SAT reduces to independent set, and follow the chain that makes vertex cover, clique, 3-coloring, subset sum, Hamiltonian cycle and the traveling salesman NP-complete.
- Recognize NP-complete problems in disguise, and the polynomial look-alikes that sit right next to them.
Decision problems, P and NP
The theory studies decision problems, whose answer is yes or no. Optimization problems have decision versions, such as "is there a tour of length at most ?", and nothing is lost: an algorithm for the optimization version answers the decision version, and binary search over turns a decision algorithm back into an optimizer with only polynomially many calls when the numbers are integers.
def verify_vertex_cover(n, edges, k, cover):
"""Is cover a set of at most k vertices touching every edge? O(n + m): a polynomial-time verifier."""
chosen = [False] * n
for v in cover:
if not 0 <= v < n:
return False
chosen[v] = True
return len(set(cover)) <= k and all(chosen[u] or chosen[v] for u, v in edges)
C5 = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)] # a 5-cycle
print(verify_vertex_cover(5, C5, 3, [0, 2, 3])) # True: every edge touches 0, 2 or 3
print(verify_vertex_cover(5, C5, 2, [0, 2])) # False: the edge (3, 4) is uncoveredChecking a proposed vertex cover is easy. Finding one of size is the hard part: no algorithm much better than trying many subsets is known in general.
| Question | Certificate for "yes" | Known to be in P? |
|---|---|---|
| Is there a path from to of length at most ? | the path | yes: Dijkstra's algorithm |
| Is the integer composite? | a factor | yes: primality testing is in P (Agrawal, Kayal & Saxena, 2002) |
| Is the CNF formula satisfiable? | a satisfying assignment | unknown: NP-complete |
| Does have a vertex cover of at most vertices? | the cover | unknown: NP-complete |
| Is there a tour through all cities of length at most ? | the tour | unknown: NP-complete |
| Is the CNF formula unsatisfiable? | none known that is short | in co-NP; not known to be in NP |
Which of these is a valid certificate for the claim " has an independent set of at least vertices", in the sense of the definition of NP?
- The size of the largest independent set of
- A list of vertices, no two of them adjacent
- A proof that no independent set has more than vertices
- The number of independent sets of size
Show the answer
B. A list of vertices, no two of them adjacent
The verifier checks the list in polynomial time: distinct vertices of , and no edge between any two of them, at most lookups. A certificate must be short and checkable without solving the problem again.
Reductions and NP-completeness
Reductions transfer algorithms. If runs in time , its output has at most bits, so a -time algorithm for decides in time
Reductions compose. A composition of polynomial-time maps is polynomial-time, so is transitive:
One NP-complete problem in P collapses NP. Every reduces to an NP-complete , so the first line puts all of them in P:
New NP-complete problems need one reduction. If is NP-complete, and , then every satisfies :
| From | To | Idea of the reduction |
|---|---|---|
| SAT | 3-SAT | split long clauses with new variables |
| 3-SAT | independent set | a triangle per clause, an edge between opposite literals (next step) |
| independent set | vertex cover | is independent exactly when covers every edge |
| independent set | clique | is independent in exactly when it is a clique in the complement of |
| 3-SAT | 3-coloring | a palette triangle, and a small gadget per variable and per clause |
| 3-SAT | subset sum | one decimal digit per variable and per clause, with no carries |
| vertex cover | Hamiltonian cycle | a gadget per edge that a tour can cross in only three ways |
| Hamiltonian cycle | traveling salesman | weight 1 on edges, 2 on non-edges: a tour of length exists exactly when a Hamiltonian cycle does |
A reduction in full: 3-SAT to independent set
An instance of independent set is a graph and a number : are there vertices with no edge between any two of them? Here is how to turn any 3-CNF formula with clauses into such an instance, so that is satisfiable exactly when the graph has an independent set of size .
Satisfiable gives an independent set. Fix a satisfying assignment, and from each clause's triangle pick one vertex whose literal is true. That is vertices, one per triangle, so no triangle edge joins two of them; and no conflict edge does either, because and are never both true.
An independent set gives an assignment. A triangle can contain at most one vertex of an independent set, so a set of size has exactly one vertex in every triangle. Its labels contain no pair , (they would be joined), so we may make all of them true at once, and set the remaining variables arbitrarily. Every clause then has a true literal.
Polynomial size. The graph has vertices, triangle edges and fewer than conflict edges, all found by comparing labels:
For example, becomes 9 vertices with 9 triangle edges and 6 conflict edges. The assignment true, false, true satisfies it, and picking in the first clause, in the second and in the third gives an independent set of size 3.
import itertools, random
def sat_to_independent_set(clauses):
"""3-CNF clauses as lists of nonzero ints (-2 means not x2) -> graph (V, E) and k."""
V = [(c, lit) for c, clause in enumerate(clauses) for lit in clause]
E = {(u, v) for u, v in itertools.combinations(range(len(V)), 2)
if V[u][0] == V[v][0] or V[u][1] == -V[v][1]} # same clause, or x and not-x
return V, E, len(clauses)
def satisfiable(clauses, n): # brute force over 2^n assignments
return any(all(any((l > 0) == b[abs(l) - 1] for l in c) for c in clauses)
for b in itertools.product([False, True], repeat=n))
def has_independent_set(V, E, k): # brute force over C(|V|, k) sets
return any(all(p not in E for p in itertools.combinations(S, 2))
for S in itertools.combinations(range(len(V)), k))
random.seed(1)
for _ in range(400):
n, m = random.randint(1, 4), random.randint(1, 6)
F = [[random.choice([1, -1]) * random.randint(1, n) for _ in range(3)] for _ in range(m)]
assert satisfiable(F, n) == has_independent_set(*sat_to_independent_set(F))
print("the reduction agrees with brute force on 400 random formulas")A reduction is an algorithm, so it can be stress-tested like one. The brute forces are exponential, which is fine on formulas this small; the reduction itself is polynomial.
In this reduction, why must the three vertices of each clause form a triangle?
- So that the graph is connected
- So that an independent set contains at most one vertex per clause, and with exactly one
- So that and are never both chosen
- So that the graph can be colored with three colors
Show the answer
B. So that an independent set contains at most one vertex per clause, and with exactly one
Without the triangles, an independent set could take two literals from one clause and none from another, and its size would no longer certify that every clause is satisfied. With them, size forces one chosen literal in each clause.
P versus NP, and the landscape around it
Four classes sit inside each other. , since a solver is a verifier that ignores the certificate. , since a machine can try every certificate in turn, reusing the same polynomial space. , since a machine with polynomial space has only exponentially many configurations, so within that many steps it halts or repeats one and loops forever.
The time hierarchy theorem (Hartmanis & Stearns, 1965) shows that more time decides strictly more problems, and in particular . So at least one of the three inclusions is strict, and nobody knows which.
If P = NP, every problem whose solutions can be checked fast could be solved fast: finding proofs, optimal schedules and keys would be as easy as checking them, since a polynomial-time decision procedure also yields solutions, one decision at a time. Public-key cryptography would collapse. The algorithms might still be impractical, with running times like , but no one expects them.
If P ≠ NP, every NP-complete problem needs superpolynomial time in the worst case. That says nothing about typical instances, small instances, approximations or special cases, which is why the next two Optimized lessons exist.
Between the two extremes, Ladner (1975) proved that if , some problems in NP are neither in P nor NP-complete. The natural candidates are factoring, which lies in , and graph isomorphism, for which Babai announced a quasipolynomial-time algorithm in 2015, running in time, and which is not NP-complete unless the polynomial hierarchy collapses.
Recognizing it
Suspect NP-hardness when a problem asks you to choose a subset, an order or an assignment under constraints that couple everything together, and none of the course's structures appears: no order of subproblems for DP, no exchange argument for greedy, no check that flips once. The hard problems rarely announce themselves:
| Everyday task | The problem in disguise |
|---|---|
| an exam timetable with slots and no student double-booked | graph -coloring |
| packing parcels into the fewest trucks | bin packing |
| visiting every customer once on the shortest route | traveling salesman |
| choosing invoices that add up to exactly a payment | subset sum |
| the largest group of people who all know each other | clique |
| the fewest cameras at junctions so that every street is watched | vertex cover |
| splitting jobs between two identical machines to finish as early as possible | partition |
| NP-complete | Polynomial look-alike | What makes it easy |
|---|---|---|
| 3-SAT | 2-SAT, linear time | two-literal clauses are implications; strongly connected components decide them |
| 3-coloring | 2-coloring, linear time | with two colors, BFS forces every color |
| Hamiltonian cycle (every vertex once) | Euler tour (every edge once), linear time | a local condition, even degrees, decides it |
| longest simple path | shortest path; longest path in a DAG | no negative cycles; no cycles at all |
| maximum cut | minimum – cut | max-flow min-cut duality |
| vertex cover | vertex cover in bipartite graphs | König's theorem: it equals a maximum matching |
| 3-dimensional matching | bipartite matching | augmenting paths |
| integer linear programming | linear programming | ellipsoid and interior-point methods (Khachiyan, 1979; Karmarkar, 1984) |
| Steiner tree (connect chosen vertices) | minimum spanning tree (connect all of them) | the cut and cycle properties |
Key takeaways
- P is solvable in polynomial time; NP has "yes" answers with short certificates checkable in polynomial time; co-NP has short certificates for "no". , and .
- is a polynomial-time map that preserves yes and no. NP-complete means in NP with every NP problem reducing to it, so one NP-complete problem in P would make P = NP.
- SAT is NP-complete (Cook–Levin), and reductions spread hardness: 3-SAT to independent set (a triangle per clause, edges between opposite literals), then vertex cover and clique by complements; 3-SAT to 3-coloring and subset sum; Hamiltonian cycle to the traveling salesman.
- Hardness hides in everyday tasks (timetables as coloring, packing, routing, exact sums), right next to polynomial look-alikes: 2-SAT, 2-coloring, Euler tours, shortest paths, minimum cuts, bipartite matching and linear programming.
- NP-hardness is a worst-case statement: small instances, special structure, approximation and solvers all remain available.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Suppose someone proves that vertex cover can be solved in polynomial time. What follows?
- Only graph problems similar to vertex cover become easy
- : every problem in NP, SAT included, becomes solvable in polynomial time
- Nothing for SAT, which is a problem about formulas, not graphs
Show the answer
B. : every problem in NP, SAT included, becomes solvable in polynomial time
Vertex cover is NP-complete: every NP problem reduces to it in polynomial time, so a polynomial algorithm for it composes with those reductions into polynomial algorithms for all of NP.
To prove a new problem NP-complete, you show that is in NP and that…
- reduces in polynomial time to a known NP-complete problem
- a known NP-complete problem reduces in polynomial time to
- no polynomial-time algorithm for is known
- has exponentially many candidate solutions
Show the answer
B. a known NP-complete problem reduces in polynomial time to
Reducing a known NP-complete problem to shows that is at least as hard as , and by transitivity every NP problem reduces to .
Subset sum has an dynamic program, where is the target. Why does this not show that P = NP?
- Because the dynamic program is incorrect for some inputs
- Because is written in about bits, so can be exponential in the length of the input
- Because subset sum is not in NP
- Because dynamic programming is not a polynomial-time technique
Show the answer
B. Because is written in about bits, so can be exponential in the length of the input
Polynomial time is measured in the number of bits of the input. A target of 60 digits is about 200 bits, yet . Such pseudo-polynomial algorithms make subset sum only weakly NP-hard; the lesson Pseudo-Polynomial Time makes this precise.
Which problem is known to lie in but not known to lie in P?
- Deciding whether a formula is satisfiable
- Deciding whether an integer is prime
- Deciding whether has a prime factor at most (factoring)
- Deciding whether a graph has a path from to
Show the answer
C. Deciding whether has a prime factor at most (factoring)
The prime factorization of certifies both answers, and its primality can be checked in polynomial time. So factoring is in , which also makes it unlikely to be NP-complete: that would give NP = co-NP. No polynomial-time algorithm is known, and much of cryptography relies on it being hard.
Go deeper
- The Cook–Levin Theorem · Why satisfiability is NP-complete: a whole computation encoded as a formula.
- A Gallery of NP-Completeness Reductions · From 3-SAT to independent set, vertex cover, Hamiltonian cycle and subset sum.
- P vs NP: Barriers & Beyond · Relativization, natural proofs, algebrization, and what is actually known.
Further reading
- M. R. Garey & D. S. Johnson, Computers and Intractability: A Guide to the Theory of NP-Completeness (W. H. Freeman, 1979).
- R. M. Karp, "Reducibility among combinatorial problems," in R. E. Miller & J. W. Thatcher (eds.), Complexity of Computer Computations (Plenum, 1972), 85–103.
- M. Sipser, Introduction to the Theory of Computation, 3rd ed. (Cengage, 2012), chapter 7.
- J. Kleinberg & É. Tardos, Algorithm Design (Pearson, 2005), chapter 8.