Some problems, like sorting or shortest paths, have fast algorithms. Others, like finding the shortest tour through 50 cities, seem to require trying exponentially many possibilities, even though checking a proposed answer is easy. Complexity theory makes this precise with the classes P (solvable quickly), NP (checkable quickly), NP-complete (the hardest problems in NP) and NP-hard. Whether P equals NP is the most famous open question in computer science, and recognizing an NP-hard problem tells you to stop hunting for a perfect polynomial algorithm and choose a coping strategy instead.
Think of it like
Sudoku: solving vs checking
Filling in a hard Sudoku can take an hour of trial and error. Checking a completed grid takes a minute: scan each row, column and box once. NP is the class of problems where checking a proposed answer is fast like that. The P vs NP question asks whether every problem that is easy to check is also easy to solve. Nearly everyone believes the answer is no, but nobody has proved it.
Decision problems and efficient algorithms
Complexity classes are defined for decision problems: questions with a yes or no answer. Optimization problems have decision versions with a threshold. "Find the shortest tour" becomes "is there a tour of length at most k?" If you can answer the decision version quickly, you can usually recover the optimum by binary searching on k.
"Efficient" means polynomial time: O(nᶜ) for some constant c, where n is the size of the input in bits. Polynomials compose (a polynomial algorithm calling a polynomial subroutine is still polynomial), and they separate cleanly from exponential growth such as 2ⁿ or n!.
- Decision problem
- A question about an input whose answer is yes or no, such as "does this graph have a Hamiltonian cycle?"
- Certificate (witness)
- A piece of evidence that an answer is yes, such as the cycle itself.
- Verifier
- An algorithm that takes an input and a certificate and checks, in polynomial time, that the certificate proves a yes answer.
- Polynomial-time reduction
- A polynomial-time transformation from instances of problem A to instances of problem B that preserves the yes/no answer. Written A ≤p B.
The class P
P is the set of decision problems that a deterministic algorithm can solve in polynomial time. Most of this site lives here: sorting, searching, shortest paths (Dijkstra's Algorithm), minimum spanning trees, maximum flow, bipartite matching, linear programming, 2-SAT, and even primality testing (the AKS algorithm, 2002).
The class NP
NP is the set of decision problems where every yes instance has a short certificate that can be verified in polynomial time. The name stands for nondeterministic polynomial time: an equivalent definition is a machine that can "guess" the certificate and then verify it.
| Problem | Certificate | Verification |
|---|---|---|
| SAT: is a Boolean formula satisfiable? | A truth assignment | Evaluate every clause: O(formula size) |
| Subset sum: does some subset sum to T? | The chosen indices | Add them up: O(n) |
| Hamiltonian cycle | An ordering of the vertices | Check each vertex appears once and consecutive pairs are edges: O(V) |
| Clique of size k | k vertices | Check all k(k − 1)/2 pairs are edges: O(k²) |
| Graph k-coloring | A color per vertex | Check every edge joins different colors: O(E) |
Reductions: comparing hardness
A reduction A ≤p B converts any instance of A into an instance of B in polynomial time, with the same answer. It says B is at least as hard as A: a fast algorithm for B would give a fast algorithm for A (transform, then solve B).
- 1
Independent set ≤p vertex cover
A set S of vertices is independent (no edge inside S) exactly when its complement V \ S touches every edge, that is, is a vertex cover. So a graph has an independent set of size k iff it has a vertex cover of size n − k.
- 2
Clique ≤p independent set
A clique in G is an independent set in the complement graph (edges flipped). Same k.
- 3
Hamiltonian cycle ≤p TSP (decision)
Give edges of G cost 1 and non-edges cost 2. G has a Hamiltonian cycle iff there is a tour of total cost at most n.
NP-complete and NP-hard
- NP-hard
- Every problem in NP reduces to it. It is at least as hard as anything in NP, and it need not be in NP itself (it may not even be a decision problem).
- NP-complete
- NP-hard and in NP. These are the hardest problems inside NP; they are all equivalent under reductions.
The Cook-Levin theorem (Cook 1971, Levin independently around 1973) proved SAT is NP-complete by encoding any polynomial-time verifier's computation as a Boolean formula. After that, proving a new problem NP-complete only takes one reduction from a known NP-complete problem. In 1972 Richard Karp did this for 21 classic problems, and thousands more have followed.
| NP-complete problem | Question | Typical reduction from |
|---|---|---|
| SAT | Can a CNF formula be satisfied? | Any NP problem (Cook-Levin) |
| 3-SAT | SAT with exactly 3 literals per clause | SAT (split long clauses) |
| Clique | Is there a complete subgraph of size k? | 3-SAT |
| Independent set / vertex cover | k mutually non-adjacent vertices / k vertices touching all edges | 3-SAT, clique |
| Hamiltonian cycle | A cycle visiting every vertex once? | 3-SAT or vertex cover |
| TSP (decision) | A tour of total length ≤ k? | Hamiltonian cycle |
| Subset sum / partition | A subset summing to T / two equal halves? | 3-SAT |
| Graph 3-coloring | Color vertices with 3 colors, no edge monochrome? | 3-SAT |
P
- Solvable in polynomial time
- Sorting, shortest paths, MST, 2-SAT, matching
NP-complete
- In NP and NP-hard
- SAT, 3-SAT, clique, vertex cover, Hamiltonian cycle, subset sum
NP-hard only
- At least as hard as NP, not known to be in NP
- TSP optimization, the halting problem (undecidable)
Is P equal to NP?
If any NP-complete problem has a polynomial-time algorithm, then every problem in NP does, and P = NP. Decades of effort have found no such algorithm, and most researchers believe P ≠ NP, but there is no proof. It is one of the Clay Mathematics Institute's Millennium Prize Problems, with a one-million-dollar reward.
Pseudo-polynomial time: the knapsack loophole
Subset sum is NP-complete, yet the classic DP solves it in O(n · T) time, where T is the target. That is not a contradiction. The input encodes T in about log₂ T bits, so O(n · T) = O(n · 2^bits): exponential in the input size. Such algorithms are called pseudo-polynomial: polynomial in the numeric value, not in the length of the input. See Knapsack Problems.
| Approach to subset sum | Time | Practical when |
|---|---|---|
| Brute force over all subsets | O(n · 2ⁿ) | n ≤ 20 or so |
| Meet in the middle | O(n · 2^(n/2)) | n ≤ 40, any target |
| DP over sums | O(n · T) | T up to about 10⁷, any n |
Problems that stay NP-hard even when all numbers are small (bounded by a polynomial in n) are strongly NP-hard: 3-SAT, TSP, bin packing, 3-partition. Subset sum and knapsack are only weakly NP-hard, which is why their DP works so well in practice.
Coping with NP-hardness
| Strategy | Idea | Example |
|---|---|---|
| Exact, exponential but pruned | Search all options, cutting hopeless branches | Backtracking, branch and bound, Held-Karp TSP in O(n² · 2ⁿ) |
| Exploit small parameters | Exponential only in a parameter k, not n (fixed-parameter tractable) | Vertex cover in O(2ᵏ · (n + m)) |
| Pseudo-polynomial DP | Exploit small numeric values | Knapsack and subset sum in O(n · W) |
| Approximation algorithms | Provably within a factor of optimal, in polynomial time | Vertex cover 2-approx; metric TSP 1.5 (Christofides); set cover ln n (greedy) |
| Heuristics and local search | Good answers fast, no guarantee | 2-opt for TSP, simulated annealing, genetic algorithms |
| SAT / ILP solvers | Encode the problem and let an industrial solver search | CDCL SAT solvers, MILP solvers for scheduling |
| Special structure | The general case is hard, but your inputs may not be | 2-SAT, trees, bipartite graphs, interval graphs, planar graphs |
Why this matters in interviews
- Many problems are NP-hard in disguise: "visit every location minimizing total distance" (TSP), "split items into two equal-sum groups" (partition), "assign jobs to k workers minimizing the finishing time" (makespan scheduling), "smallest team covering all skills" (set cover).
- When you recognize one, do not spend the interview hunting for a polynomial algorithm. Look at the constraints instead.
- Small n (≤ 20) invites bitmask DP or Backtracking; small numeric values invite pseudo-polynomial DP (Advanced DP Patterns and Knapsack Problems); large inputs with no structure call for a heuristic or approximation, stated as such.
| Constraint | Feasible complexity | Typical technique |
|---|---|---|
| n ≤ 10 to 12 | O(n!) | Permutations, brute force |
| n ≤ 20 to 25 | O(2ⁿ · n) or O(2ⁿ · n²) | Bitmask DP, subset enumeration |
| n ≤ 40 | O(2^(n/2) · n) | Meet in the middle |
| n ≤ 100, values ≤ 10⁴ | O(n · sum) | Pseudo-polynomial DP |
| n ≤ 10⁵ or more | O(n log n) | There must be special structure, or a greedy/approximate answer is expected |
Complexity
| Problem / algorithm | Time | Space | Notes |
|---|---|---|---|
| Verify a SAT assignment | O(m) | O(1) | m = total literals; this is why SAT is in NP |
| Subset sum, brute force | O(n · 2ⁿ) | O(n) | Or O(2ⁿ) with incremental sums |
| Subset sum, meet in the middle | O(n · 2^(n/2)) | O(2^(n/2)) | Sort one half, binary search the other |
| Subset sum, DP | O(n · T) | O(T) | Pseudo-polynomial |
| TSP, Held-Karp DP | O(n² · 2ⁿ) | O(n · 2ⁿ) | Versus O(n!) brute force |
| Vertex cover 2-approximation | O(V + E) | O(V) | Endpoints of a maximal matching |
Implementation
Enumerate all 2ⁿ subsets with a bitmask, or fill a boolean table of reachable sums in O(n · T).
def subset_sum_brute(nums: list[int], target: int) -> bool:
n = len(nums)
for mask in range(1 << n): # every subset: 2^n of them
total = sum(nums[i] for i in range(n) if mask >> i & 1)
if total == target:
return True
return False
def subset_sum_dp(nums: list[int], target: int) -> bool:
"""Non-negative integers. O(n * target) time: polynomial in the VALUE of target."""
reachable = [False] * (target + 1)
reachable[0] = True # the empty subset
for x in nums:
for s in range(target, x - 1, -1): # downward: each number used at most once
if reachable[s - x]:
reachable[s] = True
return reachable[target]Key takeaways
- P = problems solvable in polynomial time; NP = problems whose yes answers can be verified in polynomial time; P ⊆ NP.
- A reduction A ≤p B shows B is at least as hard as A; to prove X hard, reduce a known NP-complete problem to X.
- NP-complete problems (SAT, 3-SAT, clique, vertex cover, Hamiltonian cycle, subset sum) are all equivalent: a polynomial algorithm for one would solve them all.
- Pseudo-polynomial algorithms like the O(n · T) subset-sum DP are exponential in input bits but often practical.
- Cope with NP-hardness via pruned exact search, small parameters, approximation, heuristics, solvers or special structure.
Common pitfalls
- Reading NP as "not polynomial"; it means verifiable in nondeterministic polynomial time, and it includes all of P.
- Reducing in the wrong direction when arguing a problem is hard.
- Calling the O(n · W) knapsack DP polynomial: it is pseudo-polynomial.
- Confusing NP-hard with NP-complete: NP-hard problems need not be in NP or even be decision problems.
- Assuming every instance of an NP-hard problem is hard; real inputs often have structure or small parameters.
Interview tips
- If a problem smells like TSP, set cover, partition or scheduling, name the hardness and pivot to the constraints.
- Use the constraint table: n ≤ 20 suggests bitmask DP or backtracking; small values suggest pseudo-polynomial DP.
- If asked for large inputs anyway, offer an approximation or heuristic and state its guarantee (or lack of one).
Real-world applications
- Cryptography rests on problems believed to be hard (factoring, discrete logarithm).
- Logistics, routing and scheduling use approximation, heuristics and ILP solvers for NP-hard optimization.
- Hardware and software verification encode correctness questions as SAT instances for industrial solvers.
- Compiler register allocation (graph coloring) and instruction scheduling.
Practice problems
Test yourself
What does it mean for a decision problem to be in NP?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.