Complexity theory studies the intrinsic difficulty of computational problems. Computability asks can this be solved at all?; complexity asks how efficiently?: it bounds the time and space any algorithm needs as a function of the input size (upper bounds by algorithms, lower bounds by proofs), classifies problems into complexity classes, and compares them by reductions to find the hardest problems of a class (completeness). Core questions: can every problem whose solution is easy to verify (NP) also be solved easily (P)? Which problems are inherently exponential? How do randomness, quantum mechanics or parallelism change what is efficient? Can unconditional lower bounds be proved, or must we rely on conjectures?

For contests the practical skill is narrower: recognise NP-hardness, stop searching for a polynomial algorithm, and read the constraints for the intended escape (small , small parameter, special structure, pseudo-polynomial values).

Model of computationNotes
deterministic Turing machine (DTM)one computation path; time = transitions, space = tape cells
nondeterministic TM (NTM)accepts if some path accepts; defines NP
randomized TMrandom bits; BPP, RP, ZPP
quantum TM / quantum circuitsqubits and unitary gates; BQP
Boolean circuitsacyclic gate networks: size (gates) and depth; non-uniform
decision trees, comparison modelquery complexity; sorting lower bounds

Resource measures: time, space, alternations (quantifier switches: polynomial hierarchy), communication (bits exchanged), circuit size and depth.

Asymptotic notation

NotationDefinitionMeaning, example
upper bound: bubble sort is
lower bound: comparison sorting is
bothtight: merge sort is
strictly slower:
strictly faster:

. Polynomial: for a constant ; exponential: , broadly . Space: in place (heapsort, insertion sort), (binary search, some traversals), (merge sort, BFS), polynomial (PSPACE), exponential (brute-force SAT storing all assignments). Practical numbers per complexity are in Complexity and Analysis.

Complexity classes

ClassDefinitionIconic problems
L / NL(non)deterministic spaceundirected / directed reachability (NL-complete)
PDTM, polynomial time: “tractable”sorting, shortest paths, MST, 2-SAT, matching, flow, LP, primality (AKS)
NPNTM polynomial time = certificates verifiable in polynomial timeSAT, Hamiltonian cycle, TSP (decision), clique, vertex cover
co-NPcomplements of NP problemstautology, “no Hamiltonian cycle”
NP-completein NP and NP-hard3-SAT, clique, vertex cover, set cover, knapsack (decision)
NP-hardevery NP problem reduces to it; need not be in NPoptimization versions (TSP, max clique), the halting problem
PHconstant number of alternations: NP, co-NP, QBF with bounded alternations ( is -complete)
PSPACEpolynomial space (may take exponential time)QBF, generalized geography, Hex, Reversi, Sokoban, Rush Hour
EXPTIME timegeneralized chess, checkers, Go (Japanese ko) on boards
NEXPTIME, EXPSPACEnondeterministic exponential time, exponential spacesuccinct SAT / circuit SAT; regular expressions with squaring (EXPSPACE-complete)
#Pcounting accepting pathssat, the permanent (counting perfect matchings)
PPerror (unbounded)MAJ-SAT; contains NP
RP / co-RP / ZPP / BPPone-sided / zero / two-sided error randomized polynomial timepolynomial identity testing (co-RP), randomized quicksort (ZPP), Miller–Rabin: Randomized Algorithms
BQPquantum, bounded errorfactoring and discrete log (Shor); Grover gives a quadratic speed-up for unstructured search
QMA, NQPquantum analogues of NP (bounded / unbounded error)local Hamiltonian (QMA-complete)

Known inclusions: ; , , , , , . Known separations (hierarchy theorems, by diagonalization): , , , . Open: vs (believed different), vs co-NP, vs , vs , vs (believed equal: derandomization results under plausible assumptions), vs (believed different because of Shor), whether BQP contains NP-complete problems (believed not). If then PH collapses to P; if it collapses to NP; PH is believed infinite. Quantum computers solve SAT in with Grover: still exponential.

Reductions and completeness

ReductionDefinition
Karp (many-one) a polynomial-time with ; defines NP-completeness
Cook (Turing) polynomial time with an oracle for , several calls allowed
log-space the reduction uses space; for classes inside P (NL, P-completeness)

Proving NP-completeness: (1) show the problem is in NP (a certificate checkable in polynomial time); (2) pick a known NP-complete problem close to it; (3) build a polynomial reduction from to the new problem; (4) prove both directions of “-instance is yes constructed instance is yes”. Direction matters: reducing the new problem to a hard problem says nothing about its hardness (that is the classic error); reducing it to an easy problem gives an algorithm. Avoid constructions of exponential size.

                      SAT  (Cook-Levin: the first NP-complete problem)
                       |
                     3-SAT
        /         /    |     \             \
  3-COLORING  CLIQUE  SUBSET-SUM   HAMILTONIAN-CYCLE   3-DIM MATCHING
      |          |         |               |                 |
  planar 3-col  IND-SET  PARTITION        TSP          EXACT COVER, SET PACKING
                  |         |
             VERTEX-COVER  KNAPSACK, BIN PACKING, 3-PARTITION -> scheduling
                  |
              SET COVER, HITTING SET, DOMINATING SET -> facility location
SourceNatural targets
SAT / 3-SATlogic, constraints, circuits: circuit SAT, NAE-SAT, Max-SAT, colouring, scheduling
clique / independent setgraph existence: vertex cover, dominating set
vertex covercovering: set cover, hitting set, dominating set
Hamiltonian cycletours and paths: TSP, longest path, Steiner tree
set coverset systems: hitting set, dominating set, facility location
subset sum / partitionnumbers: knapsack, bin packing, scheduling (3-partition for strong hardness)
3-dimensional matchingpacking with triples: set packing, exact cover, partition into triangles
Euclidean TSP, geometric set covergeometry
3-partition, job shopscheduling
// 3-SAT -> Independent Set (Karp): one triangle per clause, an edge between complementary literals.
// The formula (m clauses) is satisfiable iff the graph has an independent set of size m.
pair<int, vector<pair<int, int>>> threeSatToIndependentSet(const vector<array<int, 3>>& clauses) {   // literals +-(v+1)
    int m = sz(clauses); vector<pair<int, int>> E;
    for (int c = 0; c < m; c++) for (int i = 0; i < 3; i++) for (int j = i + 1; j < 3; j++) E.push_back({3 * c + i, 3 * c + j});
    for (int a = 0; a < 3 * m; a++) for (int b = a + 1; b < 3 * m; b++)
        if (clauses[a / 3][a % 3] == -clauses[b / 3][b % 3]) E.push_back({a, b});
    return {3 * m, E};
}

The problem catalogue

DomainIn P (polynomial)
sorting and searchingcomparison sort , counting / radix / bucket sort , binary search, selection , range search
graphsBFS, DFS, topological sort, SCC, bridges, Dijkstra , Bellman–Ford , Floyd–Warshall , max flow (Dinic, push-relabel), MST, bipartite (Hopcroft–Karp) and general (blossom) matching, min-cost flow, Hungarian , Euler tours, 2-SAT, LCA, union-find, HLD
stringsKMP, Z, Rabin–Karp, suffix array, suffix automaton and tree, Aho–Corasick, tries, longest common substring
geometryconvex hull, closest pair, sweep lines, half-plane intersection, point in polygon
number theory and algebragcd, modular exponentiation, Miller–Rabin, CRT, sieve, Gaussian elimination, matrix multiplication (), FFT / NTT, LP (interior point, ellipsoid), primality (AKS)
DomainNP-complete (decision versions)
logicSAT (Cook–Levin), 3-SAT, 1-in-3 SAT, exact 3-SAT, NAE-SAT, circuit SAT, Max-SAT, weighted Max-SAT, 0-1 integer programming
graphs: cliques and coversclique, independent set, vertex cover, edge dominating set, clique cover, balanced complete bipartite subgraph
graphs: domination and colouringdominating set (total, connected, efficient), -colouring (), chromatic number, domatic number, perfect code, power domination
graphs: paths and cyclesHamiltonian cycle / path, longest path, Steiner tree, feedback vertex / arc set, disjoint paths (directed, or part of the input)
graphs: layout and structurecutwidth, bandwidth, minimum linear arrangement, bisection, max cut, maximum acyclic subgraph, subgraph isomorphism, minimum fill-in, minimum equivalent digraph, graph motif, rainbow connection
setsset cover, hitting set, exact cover (X3C), set packing, set splitting, maximum coverage, minimum test set
numberssubset sum, partition, 3-partition (strongly), knapsack, bin packing, quadratic programming, quadratic assignment, linear ordering, simultaneous Diophantine approximation
schedulingjob / open / flow shop, multiprocessor makespan, deadlines, precedence constraints, timetabling (course, exam, nurse), setup times, interval scheduling with conflicts
packing and cuttingbin packing (with conflicts), strip packing, 2D/3D packing, cutting stock, multiple knapsack, partition into triangles
routing and locationTSP and variants (capacitated VRP, repairman, rural postman, orienteering, prize-collecting, bottleneck), mixed Chinese postman, facility location, -median, -center, hub location
geometryEuclidean / rectilinear TSP and Steiner tree, geometric set cover and hitting set, art gallery, maximum independent set of geometric objects
stringsclosest string / substring, LCS and shortest common supersequence of many strings, multiple sequence alignment, bounded Post correspondence
puzzles ()Sudoku, Kakuro, Nonogram, Minesweeper consistency, Slither Link, Nurikabe, Masyu, Light Up, Battleship, Numberlink, Instant Insanity, -queens completion, peg solitaire, SameGame, Tetris, Lemmings
compilers and hardwareregister allocation, frequency assignment, Boolean formula and circuit minimization (beyond NP: -complete in general)

Karp’s 21 (1972): SAT, 0-1 integer programming, clique, set packing, vertex cover, set cover, feedback node set, feedback arc set, directed and undirected Hamiltonian cycle, 3-SAT, chromatic number, clique cover, exact cover, hitting set, Steiner tree, 3-dimensional matching, knapsack, job sequencing, partition, max cut.

NP-hard optimization (need not be in NP): TSP, max clique and independent set, min vertex cover, chromatic number, min dominating set and set cover, Steiner tree, feedback sets, max cut, layout problems; vehicle routing, traveling tournament, minimum latency; makespan and scheduling, berth allocation, gate assignment, crew scheduling; facility location, -median, -center; bin packing, strip packing, cutting stock; integer and mixed integer programming, sparse PCA, tensor rank, matrix completion, minimum rank, Boolean matrix factorization; optimal decision trees, Bayesian network structure learning, feature selection, rule-list minimization, MDL; protein folding, genome assembly, haplotyping, phylogeny (maximum parsimony), molecular docking, Ising spin glasses; VLSI layout, routing and floorplanning; maximum common subgraph, cluster editing, correlation clustering, group and directed Steiner tree, survivable network design, symbolic regression.

Beyond NPProblems
#P-completethe permanent, counting perfect matchings, counting SAT solutions: counting can be harder than deciding (finding a perfect matching is polynomial)
PSPACE-completeQBF (canonical), generalized geography, Hex, Reversi, Sokoban, Rush Hour, constraint logic, LTL model checking, planning, quantified CSP
EXPTIME-completegeneralized chess (Fraenkel–Lichtenstein), checkers (Robson), Go with Japanese ko (Robson), alternating TMs with exponential time
beyondregular expressions with squaring: EXPSPACE-complete; with complement: non-elementary; Presburger arithmetic: decidable but time (Fischer–Rabin)
undecidablehalting problem, busy beaver, Post correspondence, Entscheidungsproblem / first-order validity (Church, Turing), Rice’s theorem (every non-trivial semantic property, e.g. program equivalence), Hilbert’s tenth problem (Matiyasevich), word problem for semigroups and groups, matrix mortality (from ), Wang tiling

Easy–hard pairs worth memorising

HardEasy neighbour
3-SAT2-SAT: linear, SCC
3-colouring2-colouring (bipartiteness)
Hamiltonian path / cycleEuler path / circuit
longest path in a general graphlongest path in a DAG
vertex cover, independent set in general graphsbipartite graphs (Kőnig, matching)
max cutmin cut
integer programminglinear programming
TSPMST, shortest paths
subset sum, knapsackpseudo-polynomial DP when values are small (weakly NP-hard)
counting perfect matchingsdeciding a perfect matching; counting spanning trees (matrix–tree)
graph isomorphismquasi-polynomial (Babai 2015): not known to be in P or NP-complete
factoringin NP co-NP, not believed NP-complete
Weakly NP-hardStrongly NP-hard
pseudo-polynomial algorithmexistsnone unless P = NP
FPTASpossibleimpossible unless P = NP
examplessubset sum, knapsack, partitionTSP, bin packing, 3-partition, clique

Knapsack’s DP is polynomial in the value but exponential in its length : that is what “pseudo-polynomial” and “weakly NP-hard” mean, and why knapsack has an FPTAS (Approximation Algorithms) but TSP does not.

When you recognise NP-hardness

Stop looking for a polynomial exact algorithm and read the constraints:

ConstraintApproach
bitmask DP over subsets
–meet in the middle
, sparse or structuredbranch and bound, good pruning
a small parameter (solution size, terminals, special vertices)FPT algorithm, subset DP over the items
bounded values ()pseudo-polynomial DP
the graph is a treetree DP: independent set, dominating set, vertex cover, colouring, Steiner tree are all linear on trees
bipartitematching and flow
planarseparators, specialised algorithms
small treewidth, cactusDP over a tree decomposition
scored / marathon taskheuristics: Heuristic Optimization
Best known exact algorithmsTimeSpace
TSP, Hamiltonian cycle (Held–Karp)
maximum independent set / clique (branching)polynomial
vertex cover (FPT branching)polynomial
graph colouring (inclusion–exclusion)
Steiner tree (Dreyfus–Wagner) (plus shortest paths)
dominating set (branch and reduce)polynomial
set cover over a universe of size DP
0/1 knapsack DP or meet in the middle
bin packing, job shop, quadratic assignmentbranch and bound, ILPexponential

Parameterized complexity

A problem is fixed-parameter tractable (FPT) in a parameter if it is solvable in : the explosion is confined to . is not FPT (the exponent depends on ): that is the class XP. Two independent sizes in the constraints ( large, tiny) is the signature of an FPT problem.

Running timeClass,
FPT, fine
FPT, fine
FPT, too slow (but FPT)
XPastronomical
ProblemParameterBest known
vertex coversolution size (Chen, Kanj, Xia)
feedback vertex set deterministic, randomized
-path (algebraic); color coding : Randomized Search
Steiner treeterminals : Steiner Tree
-hitting set
closest stringnumber of stringsFPT
anything MSO-definabletreewidth (Courcelle); typical DPs
independent set / cliquesizeW[1]-hard
dominating set, set cover (number of sets)sizeW[2]-hard
colouringnumber of coloursnot FPT unless P = NP (NP-hard for 3)

; W[1]-hardness is the parameterized NP-hardness (no FPT algorithm unless FPT = W[1], Downey–Fellows). Note the asymmetry: vertex cover is FPT in , but its complement, independent set, is W[1]-hard in its size.

StructureTreewidth
tree, forest1
cycle, cactus, series-parallel, outerplanar2
grid
planar
complete graph

Kernelization reduces an instance in polynomial time to an equivalent one whose size depends only on , then solves the kernel by brute force. Buss’s kernel for vertex cover: a vertex of degree must be in the cover (otherwise all its neighbours are); delete isolated vertices; if more than edges remain, answer no. The Nemhauser–Trotter LP gives a -vertex kernel. A decidable problem is FPT iff it has a kernel.

// Is there a vertex cover of size <= k? Buss kernel + branching on an edge: O(2^k k^2 + n + m).
bool vertexCoverAtMostK(int n, vector<pair<int, int>> E, int k) {
    while (true) {                                          // kernel: take vertices of degree > k
        if (k < 0) return false;
        vector<int> deg(n, 0); for (auto [u, v] : E) deg[u]++, deg[v]++;
        int big = -1; for (int v = 0; v < n; v++) if (deg[v] > k) { big = v; break; }
        if (big < 0) break;
        vector<pair<int, int>> F; for (auto e : E) if (e.first != big && e.second != big) F.push_back(e);
        E = F; k--;
    }
    if ((ll)sz(E) > (ll)k * k) return false;               // each cover vertex covers <= k edges
    auto branch = [&](auto&& self, const vector<pair<int, int>>& es, int kk) -> bool {
        if (es.empty()) return true;
        if (kk == 0) return false;
        auto [u, v] = es[0];
        for (int w : {u, v}) {                              // one endpoint of the edge is in the cover
            vector<pair<int, int>> F; for (auto e : es) if (e.first != w && e.second != w) F.push_back(e);
            if (self(self, F, kk - 1)) return true;
        }
        return false;
    };
    return branch(branch, E, k);
}

Lower bounds

A lower bound proves that every algorithm in a stated model needs some amount of work. Reading an arbitrary input can require probes; outputting objects needs (printing all subsets is exponential even if each next subset is cheap); NP-hardness is conditional evidence, not a proven exponent, and an exponential known algorithm proves nothing about lower bounds.

TechniqueExample
decision treescomparison sorting needs comparisons; searching a sorted array needs
adversary argumentsfinding the maximum needs comparisons; minimum and maximum together need ; detecting a marked value needs probes
information / countingany algorithm distinguishing outcomes needs bits of answers
reductionssorting convex hull gives for hulls (algebraic decision trees)
communication complexityset disjointness needs bits even with randomness; used for streaming and data-structure bounds
fine-grained (conditional)SETH: no edit distance or LCS; 3SUM: no for many geometric problems; APSP conjecture

P vs NP and the rest of the landscape

P vs NP (a Millennium Prize problem): if , every NP-complete problem is efficiently solvable, which would transform optimization, AI and mathematics (automated proof search) and break cryptography based on factoring and discrete logarithms. If (the general belief), easy verification does not imply easy solving, which justifies approximation algorithms and cryptographic hardness assumptions. Evidence: decades without a polynomial algorithm for any NP-complete problem, the collapse of PH that would cause, and barrier results (relativization, natural proofs, algebrization) explaining why standard techniques cannot settle it. NP does not mean “non-polynomial”: every problem in P is in NP. Optimization problems are compared through their decision versions (“is there a tour of length ?”); certificates make membership in NP concrete (a Hamiltonian path is an ordering of the vertices: check adjacency and uniqueness; subset sum: the subset; 3-colourability: the colouring).

Circuit complexity (non-uniform; a circuit per input size; uniform families connect to TMs): NC (polynomial size, polylog depth: efficiently parallelizable; has depth ), AC⁰ (constant depth, unbounded fan-in AND/OR, NOT), AC⁰[m] (with MOD gates), ACC⁰ (any moduli), TC⁰ (threshold / MAJORITY gates), P/poly (polynomial size; contains P and BPP). Known: parity is not in AC⁰, so ; (Williams, 2011). Open: whether (showing would prove ), and even whether ; general circuit lower bounds are notoriously hard.

Communication complexity: bits that parties holding parts of the input must exchange (deterministic, randomized, quantum). Lower bounds via the rank of the communication matrix (approximate rank for randomized protocols); quantum communication can be exponentially smaller for some functions. Applications: circuit lower bounds, streaming, distributed databases, VLSI.

Descriptive complexity (logics on finite ordered structures): (Fagin, 1974), (Immerman–Vardi), , , second-order logic. Applications: database query languages, finite model theory.

Approximation and inapproximability (details and algorithms in Approximation Algorithms): ratio means cost (minimization) or (maximization); hardness via gap reductions and the PCP theorem.

ProblemBest ratio knownHardness
metric TSP (Karlin, Klein, Oveis Gharan 2021; Christofides )no PTAS: NP-hard within
general TSPnoneno constant ratio unless P = NP
vertex cover2NP-hard below (Khot–Minzer–Safra; earlier 1.3606, Dinur–Safra); under the Unique Games Conjecture
set cover (greedy) (Dinur–Steurer)
max cut0.878 (Goemans–Williamson); 0.878 is tight under UGC
knapsackFPTASnone (weakly NP-hard)
bin packingabsolute ; asymptotically absolute is NP-hard (from partition)
max clique (Feige) (Håstad, Zuckerman)

PTAS: -approximation in ; FPTAS: in . The Unique Games Conjecture (Khot) would make many of these ratios tight; it is open.

Exercises

Describe certificates for subset sum and 3-colourability and contrast verifying with finding them. Given and only special vertices, design a state over the special vertices instead of all vertices. Reduce bipartite matching to flow and prove that integral unit flows correspond exactly to matchings. Derive the comparison lower bound for the insertion position in a sorted array. Explain why printing all subsets has an exponential output lower bound. Show how pairwise comparisons find minimum and maximum together faster than two scans.

Resources

  • Garey and Johnson, Computers and Intractability (the NP-completeness catalogue); Papadimitriou, Computational Complexity; Sipser, Introduction to the Theory of Computation; Arora and Barak, Computational Complexity: A Modern Approach; Vazirani, Approximation Algorithms; Downey and Fellows, Parameterized Complexity.
  • Complexity Zoo (complexityzoo.net); Wikipedia’s list of NP-complete problems and Karp’s 21; the Compendium of NP Optimization Problems (Crescenzi and Kann); the Open Problem Garden.
  • Repositories: graphofnpcompletereductions (a graph of reductions), CodingThrust/problem-reductions, lawliet89/np-complete, GauravBh1010tt/Solving-NP-Hard-problems.