Simple Algorithm
Algorithms & Data Structures · Optimized · 24 min

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 P⊆NP⊆PSPACE⊆EXP\mathrm{P} \subseteq \mathrm{NP} \subseteq \mathrm{PSPACE} \subseteq \mathrm{EXP}.
  • 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 LL?", and nothing is lost: an algorithm for the optimization version answers the decision version, and binary search over LL turns a decision algorithm back into an optimizer with only polynomially many calls when the numbers are integers.

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

Checking a proposed vertex cover is easy. Finding one of size kk is the hard part: no algorithm much better than trying many subsets is known in general.

QuestionCertificate for "yes"Known to be in P?
Is there a path from ss to tt of length at most LL?the pathyes: Dijkstra's algorithm
Is the integer NN composite?a factoryes: primality testing is in P (Agrawal, Kayal & Saxena, 2002)
Is the CNF formula satisfiable?a satisfying assignmentunknown: NP-complete
Does GG have a vertex cover of at most kk vertices?the coverunknown: NP-complete
Is there a tour through all cities of length at most LL?the tourunknown: NP-complete
Is the CNF formula unsatisfiable?none known that is shortin co-NP; not known to be in NP
For composite numbers a factor is the obvious certificate, but deciding without one, by an efficient algorithm, took until 2002.
Check your understanding

Which of these is a valid certificate for the claim "GG has an independent set of at least kk vertices", in the sense of the definition of NP?

  1. The size of the largest independent set of GG
  2. A list of kk vertices, no two of them adjacent
  3. A proof that no independent set has more than kk vertices
  4. The number of independent sets of size kk
Show the answer

B. A list of kk vertices, no two of them adjacent

The verifier checks the list in polynomial time: kk distinct vertices of GG, and no edge between any two of them, at most (k2)\binom{k}{2} lookups. A certificate must be short and checkable without solving the problem again.

Reductions and NP-completeness

DerivationWhy one reduction is enough
  1. p(n)+q(p(n))  =  nO(1)⟹A≤pB, B∈P  ⇒  A∈Pp(n) + q\big(p(n)\big) \;=\; n^{O(1)} \qquad\Longrightarrow\qquad A \le_p B,\ B \in \mathrm{P} \;\Rightarrow\; A \in \mathrm{P}

    Reductions transfer algorithms. If ff runs in time p(n)p(n), its output has at most p(n)p(n) bits, so a q(n)q(n)-time algorithm for BB decides AA in time

  2. A≤pB  and  B≤pC    ⟹    A≤pCA \le_p B \ \text{ and } \ B \le_p C \;\;\Longrightarrow\;\; A \le_p C

    Reductions compose. A composition of polynomial-time maps is polynomial-time, so ≤p\le_p is transitive:

  3. B NP-complete, B∈P    ⟹    P=NPB \text{ NP-complete},\ B \in \mathrm{P} \;\;\Longrightarrow\;\; \mathrm{P} = \mathrm{NP}

    One NP-complete problem in P collapses NP. Every L∈NPL \in \mathrm{NP} reduces to an NP-complete BB, so the first line puts all of them in P:

  4. A NP-complete, A≤pB, B∈NP    ⟹    B NP-completeA \text{ NP-complete},\ A \le_p B,\ B \in \mathrm{NP} \;\;\Longrightarrow\;\; B \text{ NP-complete}

    New NP-complete problems need one reduction. If AA is NP-complete, A≤pBA \le_p B and B∈NPB \in \mathrm{NP}, then every L∈NPL \in \mathrm{NP} satisfies L≤pA≤pBL \le_p A \le_p B:

FromToIdea of the reduction
SAT3-SATsplit long clauses with new variables
3-SATindependent seta triangle per clause, an edge between opposite literals (next step)
independent setvertex coverSS is independent exactly when V∖SV \setminus S covers every edge
independent setcliqueSS is independent in GG exactly when it is a clique in the complement of GG
3-SAT3-coloringa palette triangle, and a small gadget per variable and per clause
3-SATsubset sumone decimal digit per variable and per clause, with no carries
vertex coverHamiltonian cyclea gadget per edge that a tour can cross in only three ways
Hamiltonian cycletraveling salesmanweight 1 on edges, 2 on non-edges: a tour of length nn exists exactly when a Hamiltonian cycle does
Karp (1972) proved 21 problems NP-complete with chains like this one, and Garey & Johnson (1979) catalog hundreds. The Optimal lesson A Gallery of NP-Completeness Reductions proves every row.

A reduction in full: 3-SAT to independent set

An instance of independent set is a graph GG and a number kk: are there kk vertices with no edge between any two of them? Here is how to turn any 3-CNF formula φ\varphi with mm clauses into such an instance, so that φ\varphi is satisfiable exactly when the graph has an independent set of size mm.

DerivationProof
  1. S={one true literal per clause},∣S∣=m,S independentS = \{\text{one true literal per clause}\}, \qquad \abs{S} = m, \quad S \text{ independent}

    Satisfiable gives an independent set. Fix a satisfying assignment, and from each clause's triangle pick one vertex whose literal is true. That is mm vertices, one per triangle, so no triangle edge joins two of them; and no conflict edge does either, because xx and ¬x\neg x are never both true.

  2. ∣S∩trianglej∣=1  ∀j⟹a consistent assignment satisfying φ\abs{S \cap \text{triangle}_j} = 1 \ \ \forall j \quad\Longrightarrow\quad \text{a consistent assignment satisfying } \varphi

    An independent set gives an assignment. A triangle can contain at most one vertex of an independent set, so a set of size mm has exactly one vertex in every triangle. Its labels contain no pair xx, ¬x\neg x (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.

  3. ∣V∣=3m,∣E∣  ≤  (3m2)=O(m2),construction time O(m2)\abs{V} = 3m, \qquad \abs{E} \;\le\; \tbinom{3m}{2} = O(m^2), \qquad \text{construction time } O(m^2)

    Polynomial size. The graph has 3m3m vertices, 3m3m triangle edges and fewer than (3m2)\binom{3m}{2} conflict edges, all found by comparing labels:

For example, (x1∨¬x2∨x3)∧(¬x1∨x2∨x3)∧(¬x1∨¬x2∨¬x3)(x_1 \lor \neg x_2 \lor x_3) \land (\neg x_1 \lor x_2 \lor x_3) \land (\neg x_1 \lor \neg x_2 \lor \neg x_3) becomes 9 vertices with 9 triangle edges and 6 conflict edges. The assignment x1=x_1 = true, x2=x_2 = false, x3=x_3 = true satisfies it, and picking x1x_1 in the first clause, x3x_3 in the second and ¬x2\neg x_2 in the third gives an independent set of size 3.

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

Check your understanding

In this reduction, why must the three vertices of each clause form a triangle?

  1. So that the graph is connected
  2. So that an independent set contains at most one vertex per clause, and with k=mk = m exactly one
  3. So that xx and ¬x\neg x are never both chosen
  4. 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 k=mk = m 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 mm forces one chosen literal in each clause.

P versus NP, and the landscape around it

Four classes sit inside each other. P⊆NP\mathrm{P} \subseteq \mathrm{NP}, since a solver is a verifier that ignores the certificate. NP⊆PSPACE\mathrm{NP} \subseteq \mathrm{PSPACE}, since a machine can try every certificate in turn, reusing the same polynomial space. PSPACE⊆EXP\mathrm{PSPACE} \subseteq \mathrm{EXP}, 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 P≠EXP\mathrm{P} \ne \mathrm{EXP}. 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 n100n^{100}, 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 P≠NP\mathrm{P} \ne \mathrm{NP}, some problems in NP are neither in P nor NP-complete. The natural candidates are factoring, which lies in NP∩co-NP\mathrm{NP} \cap \text{co-NP}, and graph isomorphism, for which Babai announced a quasipolynomial-time algorithm in 2015, running in exp⁡((log⁡n)O(1))\exp\big((\log n)^{O(1)}\big) 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 taskThe problem in disguise
an exam timetable with k≥3k \ge 3 slots and no student double-bookedgraph kk-coloring
packing parcels into the fewest trucksbin packing
visiting every customer once on the shortest routetraveling salesman
choosing invoices that add up to exactly a paymentsubset sum
the largest group of people who all know each otherclique
the fewest cameras at junctions so that every street is watchedvertex cover
splitting jobs between two identical machines to finish as early as possiblepartition
All of these are NP-hard in general.
NP-completePolynomial look-alikeWhat makes it easy
3-SAT2-SAT, linear timetwo-literal clauses are implications; strongly connected components decide them
3-coloring2-coloring, linear timewith two colors, BFS forces every color
Hamiltonian cycle (every vertex once)Euler tour (every edge once), linear timea local condition, even degrees, decides it
longest simple pathshortest path; longest path in a DAGno negative cycles; no cycles at all
maximum cutminimum ss–tt cutmax-flow min-cut duality
vertex coververtex cover in bipartite graphsKönig's theorem: it equals a maximum matching
3-dimensional matchingbipartite matchingaugmenting paths
integer linear programminglinear programmingellipsoid 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
One small change, a third literal, a third color, every vertex instead of every edge, moves a problem across the line.

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". P⊆NP⊆PSPACE⊆EXP\mathrm{P} \subseteq \mathrm{NP} \subseteq \mathrm{PSPACE} \subseteq \mathrm{EXP}, and P≠EXP\mathrm{P} \ne \mathrm{EXP}.
  • A≤pBA \le_p B 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.

Question 1

Suppose someone proves that vertex cover can be solved in polynomial time. What follows?

  1. Only graph problems similar to vertex cover become easy
  2. P=NP\mathrm{P} = \mathrm{NP}: every problem in NP, SAT included, becomes solvable in polynomial time
  3. Nothing for SAT, which is a problem about formulas, not graphs
  4. P≠NP\mathrm{P} \ne \mathrm{NP}
Show the answer

B. P=NP\mathrm{P} = \mathrm{NP}: 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.

Question 2

To prove a new problem XX NP-complete, you show that XX is in NP and that…

  1. XX reduces in polynomial time to a known NP-complete problem
  2. a known NP-complete problem reduces in polynomial time to XX
  3. no polynomial-time algorithm for XX is known
  4. XX has exponentially many candidate solutions
Show the answer

B. a known NP-complete problem reduces in polynomial time to XX

Reducing a known NP-complete problem AA to XX shows that XX is at least as hard as AA, and by transitivity every NP problem reduces to XX.

Question 3

Subset sum has an O(nT)O(nT) dynamic program, where TT is the target. Why does this not show that P = NP?

  1. Because the dynamic program is incorrect for some inputs
  2. Because TT is written in about log⁡2T\log_2 T bits, so O(nT)O(nT) can be exponential in the length of the input
  3. Because subset sum is not in NP
  4. Because dynamic programming is not a polynomial-time technique
Show the answer

B. Because TT is written in about log⁡2T\log_2 T bits, so O(nT)O(nT) 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 T≈1060T \approx 10^{60}. Such pseudo-polynomial algorithms make subset sum only weakly NP-hard; the lesson Pseudo-Polynomial Time makes this precise.

Question 4

Which problem is known to lie in NP∩co-NP\mathrm{NP} \cap \text{co-NP} but not known to lie in P?

  1. Deciding whether a formula is satisfiable
  2. Deciding whether an integer is prime
  3. Deciding whether NN has a prime factor at most kk (factoring)
  4. Deciding whether a graph has a path from ss to tt
Show the answer

C. Deciding whether NN has a prime factor at most kk (factoring)

The prime factorization of NN certifies both answers, and its primality can be checked in polynomial time. So factoring is in NP∩co-NP\mathrm{NP} \cap \text{co-NP}, 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

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.