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.

Advanced 8 min readLesson 9 of 9 Interview Q&A

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 — O(nc)O(n^c) 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 — O(2n)O(2^n) — becomes hopeless around n = 50–60 (Complexity analysis).

P and NP

ClassDefinitionExamples
PProblems solvable in polynomial timeSorting, shortest paths, minimum spanning tree, maximum flow, bipartite matching, primality testing, linear programming, 2-SAT
NPProblems 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.

NP-hardat least as hard as everything in NP (may not be in NP — e.g. halting problem, optimisation versions)NP-completein NP and NP-hard: SAT, 3-colouring, Hamiltonian cycle, subset sum, TSP (decision)NPsolutions verifiable in polynomial timePsolvable in polynomial time

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:

  1. Show X ∈ NP (a certificate can be checked in polynomial time).
  2. 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

ProblemQuestion
SAT / 3-SATCan this Boolean formula (with clauses of 3 literals) be satisfied?
Vertex coverCan k vertices touch every edge?
Independent set / cliqueAre there k mutually non-adjacent / adjacent vertices?
Graph colouring (k ≥ 3)Can the graph be coloured with k colours? (Graph theory)
Hamiltonian cycleIs there a cycle visiting every vertex once?
Travelling salesman (decision)Is there a tour of total length ≤ k?
Subset sum / partition / knapsackDoes some subset hit the target exactly?
Bin packingDo the items fit in k bins?
Set coverCan 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 PNP-complete
Shortest pathLongest simple path
Euler circuit (each edge once)Hamiltonian cycle (each vertex once)
2-SAT3-SAT
2-colouring (bipartite test)3-colouring
Minimum spanning treeSteiner tree, TSP
Bipartite matching3-dimensional matching
Linear programmingInteger 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:

StrategyIdeaExamples
Approximation algorithmsGuaranteed within a factor of optimalVertex cover within 2×; metric TSP within 1.5× (Christofides); greedy set cover within ln n
Heuristics and metaheuristicsGood solutions fast, no guaranteeGreedy, local search (2-opt for TSP), simulated annealing, genetic algorithms, tabu search
Exact solvers on real instancesClever search that's fast in practiceSAT solvers (CDCL), ILP solvers (Gurobi, OR-Tools), constraint programming — solve industrial instances with millions of variables
Exponential but smarterBetter basesHeld–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) algorithmsExponential only in a small parameter kVertex cover in O(2ᵏ · n)
Special structureThe general problem is hard; your inputs may not beColouring interval graphs, TSP on trees, 2-SAT, bounded treewidth
Small nBrute force or bitmask DP when n ≤ ~20Subset 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

ClassMeaningExample
co-NP"No" answers have short certificatesTautology, "this formula is unsatisfiable"
PSPACESolvable with polynomial memory (any time)Generalised chess/Go on n × n boards, QBF, regex equivalence
EXPTIMESolvable in exponential timeGeneralised chess (EXPTIME-complete) — provably not in P
BPPSolvable in polynomial time by randomised algorithms with bounded errorPolynomial identity testing; widely believed to equal P
BQPEfficient on quantum computersFactoring (Shor) — but NP-complete problems are not believed to be in BQP
UndecidableNo algorithm at allHalting 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.

Key takeaways
  • 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.
Interview questions
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.