Complexity Classes
P, NP, NP-complete and NP-hard explained — decision problems, verification vs solving, polynomial-time reductions, the Cook–Levin theorem, classic NP-complete problems, P vs NP, coping strategies (approximation, heuristics, parameterised and exponential algorithms), plus PSPACE, EXP and BPP.
Computability asks whether a problem can be solved at all. Complexity theory asks how much time (or space) it takes — and sorts problems into classes. Its most famous open question, P vs NP, is one of the Millennium Prize Problems, with a one-million-dollar prize.
For most engineers, the practical skill is recognising when a problem is NP-hard, so you stop searching for a fast exact algorithm and reach for the right compromise.
Decision problems and polynomial time
Complexity classes are defined for decision problems (yes/no answers). Optimisation problems have decision versions: "what's the shortest tour?" becomes "is there a tour of length ≤ k?"
Polynomial time — for some constant c — is the formal notion of "efficient". It's robust (the same across reasonable machine models) and composable (a polynomial number of polynomial steps is polynomial). Exponential time — — becomes hopeless around n = 50–60 (Complexity analysis).
P and NP
| Class | Definition | Examples |
|---|---|---|
| P | Problems solvable in polynomial time | Sorting, shortest paths, minimum spanning tree, maximum flow, bipartite matching, primality testing, linear programming, 2-SAT |
| NP | Problems whose "yes" answers can be verified in polynomial time given a certificate (a proposed solution) | Everything in P, plus SAT, travelling salesman (decision), graph colouring, subset sum, Sudoku |
NP stands for nondeterministic polynomial time: a machine that could "guess" the certificate and then check it. It does not mean "not polynomial".
Example — Sudoku. Solving an n² × n² Sudoku is hard. But given a filled grid, checking every row, column and box takes polynomial time. Likewise for a proposed graph colouring, a proposed tour under length k, or a proposed subset summing to a target.
P vs NP
Clearly P ⊆ NP (if you can solve it, you can verify it by solving it). Is P = NP? — can every problem whose solutions are easy to check also be solved easily?
Almost everyone believes P ≠ NP, but no one has proved it. If P = NP (with a practical algorithm):
- Most public-key cryptography would collapse (finding keys is in NP) (Public-key cryptography).
- Optimal scheduling, routing, chip layout, protein folding and many AI problems would become easy.
- Finding mathematical proofs (of bounded length) would be as easy as checking them.
Reductions and NP-completeness
A polynomial-time reduction from A to B transforms any instance of A into an instance of B with the same answer, in polynomial time. If A reduces to B, then B is at least as hard as A: a fast algorithm for B gives a fast algorithm for A.
- NP-hard: every problem in NP reduces to it.
- NP-complete: NP-hard and in NP — the hardest problems in NP.
If any NP-complete problem has a polynomial-time algorithm, then P = NP. Thousands of NP-complete problems are known; none has a known polynomial algorithm.
Cook–Levin: the first NP-complete problem
SAT — is there an assignment making a Boolean formula true? — is NP-complete (Cook 1971, Levin 1973). The proof encodes the computation of any polynomial-time verifier as a Boolean formula. In 1972, Karp then reduced SAT to 21 other problems, showing they're all NP-complete.
To prove a new problem X is NP-complete:
- Show X ∈ NP (a certificate can be checked in polynomial time).
- Take a known NP-complete problem Y and give a polynomial-time reduction from Y to X.
Direction matters: reduce the known hard problem to your problem.
Classic NP-complete problems
| Problem | Question |
|---|---|
| SAT / 3-SAT | Can this Boolean formula (with clauses of 3 literals) be satisfied? |
| Vertex cover | Can k vertices touch every edge? |
| Independent set / clique | Are there k mutually non-adjacent / adjacent vertices? |
| Graph colouring (k ≥ 3) | Can the graph be coloured with k colours? (Graph theory) |
| Hamiltonian cycle | Is there a cycle visiting every vertex once? |
| Travelling salesman (decision) | Is there a tour of total length ≤ k? |
| Subset sum / partition / knapsack | Does some subset hit the target exactly? |
| Bin packing | Do the items fit in k bins? |
| Set cover | Can k sets cover the universe? |
| Scheduling with constraints, timetabling, Sudoku, Minesweeper consistency, Tetris | — |
Easy vs hard twins
Tiny changes in a problem can cross the line:
| In P | NP-complete |
|---|---|
| Shortest path | Longest simple path |
| Euler circuit (each edge once) | Hamiltonian cycle (each vertex once) |
| 2-SAT | 3-SAT |
| 2-colouring (bipartite test) | 3-colouring |
| Minimum spanning tree | Steiner tree, TSP |
| Bipartite matching | 3-dimensional matching |
| Linear programming | Integer linear programming |
Pseudo-polynomial time
Knapsack and subset sum are NP-complete, yet the DP runs in O(n · W) (DP classics). No contradiction: W is a number in the input, written with only log W bits, so O(n · W) is exponential in the input size. These algorithms are pseudo-polynomial — fast when the numbers are small. (Strongly NP-hard problems such as bin packing and 3-partition have no such algorithm unless P = NP.)
Coping with NP-hard problems
NP-hardness is a statement about the worst case for exact solutions on all inputs. Relax any of those:
| Strategy | Idea | Examples |
|---|---|---|
| Approximation algorithms | Guaranteed within a factor of optimal | Vertex cover within 2×; metric TSP within 1.5× (Christofides); greedy set cover within ln n |
| Heuristics and metaheuristics | Good solutions fast, no guarantee | Greedy, local search (2-opt for TSP), simulated annealing, genetic algorithms, tabu search |
| Exact solvers on real instances | Clever search that's fast in practice | SAT solvers (CDCL), ILP solvers (Gurobi, OR-Tools), constraint programming — solve industrial instances with millions of variables |
| Exponential but smarter | Better bases | Held–Karp DP for TSP in O(n² 2ⁿ) instead of O(n!); meet-in-the-middle for subset sum; branch and bound; backtracking with pruning (Backtracking) |
| Parameterised (FPT) algorithms | Exponential only in a small parameter k | Vertex cover in O(2ᵏ · n) |
| Special structure | The general problem is hard; your inputs may not be | Colouring interval graphs, TSP on trees, 2-SAT, bounded treewidth |
| Small n | Brute force or bitmask DP when n ≤ ~20 | Subset enumeration |
Interview tip: if a problem looks like TSP, knapsack, scheduling, set cover or colouring, say so, state it's NP-hard in general, and then propose a DP for small inputs, a greedy/approximation for large ones, or note special constraints that make it tractable.
Beyond P and NP
| Class | Meaning | Example |
|---|---|---|
| co-NP | "No" answers have short certificates | Tautology, "this formula is unsatisfiable" |
| PSPACE | Solvable with polynomial memory (any time) | Generalised chess/Go on n × n boards, QBF, regex equivalence |
| EXPTIME | Solvable in exponential time | Generalised chess (EXPTIME-complete) — provably not in P |
| BPP | Solvable in polynomial time by randomised algorithms with bounded error | Polynomial identity testing; widely believed to equal P |
| BQP | Efficient on quantum computers | Factoring (Shor) — but NP-complete problems are not believed to be in BQP |
| Undecidable | No algorithm at all | Halting problem |
Known: P ⊆ NP ⊆ PSPACE ⊆ EXPTIME, and P ≠ EXPTIME (the time hierarchy theorem). Which of the intermediate inclusions are strict remains open.
Note on factoring: it's in NP (and co-NP) but not known to be NP-complete, and is widely believed not to be. RSA's security rests on factoring being hard in practice, not on P ≠ NP.
- P: solvable in polynomial time. NP: solutions verifiable in polynomial time. P ⊆ NP; whether P = NP is open.
- NP-hard: at least as hard as all of NP; NP-complete: NP-hard and in NP — a polynomial algorithm for one would give P = NP.
- Prove NP-completeness by showing membership in NP and reducing a known NP-complete problem to yours.
- SAT was first (Cook–Levin); classics include 3-SAT, vertex cover, colouring, Hamiltonian cycle, TSP, subset sum.
- Small changes flip difficulty: shortest vs longest path, Euler vs Hamiltonian, 2-SAT vs 3-SAT.
- Knapsack's O(nW) DP is pseudo-polynomial.
- Cope with approximation, heuristics, SAT/ILP solvers, smarter exponential or parameterised algorithms, and special structure.
QWhat is the difference between NP-hard and NP-complete?medium
An NP-complete problem is both in NP — a proposed solution can be verified in polynomial time — and NP-hard — every problem in NP reduces to it in polynomial time. An NP-hard problem need only satisfy the second condition, so it can be outside NP: the optimisation version of TSP, or even undecidable problems like the halting problem. NP-complete problems are the hardest problems inside NP; if any one is solvable in polynomial time, then P = NP.
QYou're asked to find the optimal delivery route visiting 200 stops. How do you respond?hard
Recognise it as a travelling salesman variant, which is NP-hard, so exact optimality for 200 stops isn't realistic with brute force or Held–Karp. In practice: build a good tour with a construction heuristic (nearest neighbour, savings algorithm, or Christofides for a 1.5× guarantee on metric distances), improve it with local search such as 2-opt or Or-opt, possibly with simulated annealing, and use a solver like OR-Tools or an ILP/branch-and-cut solver if near-optimal results justify the compute. Consider real constraints — time windows, vehicle capacity — and whether clustering stops by region decomposes the problem.