P vs NP and NP-Completeness, Explained Plainly
Some problems have fast algorithms: sorting, shortest paths, checking whether a number is in a list. For others, such as filling a knapsack perfectly or finding the shortest route through many cities, every known exact algorithm takes exponential time in the worst case. P versus NP asks whether that second group is truly harder or whether we simply have not found the fast algorithms yet. Nobody knows. This guide explains the terms precisely (decision problems, P, NP, NP-hard and NP-complete), shows a reduction, and covers what a programmer actually does when a problem turns out to be NP-hard.
Decision problems
Complexity classes are defined for decision problems: questions with a yes or no answer. "What is the shortest tour through these cities?" is an optimization problem; its decision version is "is there a tour of total length at most k?". The two are closely linked. If you can answer the yes/no version quickly, you can usually find the optimum quickly too, by searching over k. Working with yes/no questions keeps the definitions simple.
Running time is measured in the size of the input written down, in bits or symbols. That detail matters later.
P: solvable in polynomial time
P is the class of decision problems that some algorithm solves in O(n^k) time for some constant k, where n is the input size. "Is this list sorted?", "is there a path from s to t in this graph?" and "does this graph have a cycle?" are all in P. Polynomial time is the formal stand-in for "efficient". An O(n^50) algorithm would be useless in practice, so "in P" and "fast in practice" are not the same thing; what the definition captures is the gulf between polynomial and exponential growth.
NP: checkable in polynomial time
NP is the class of decision problems where, whenever the answer is yes, there is a short proof of it (a certificate) that can be checked in polynomial time. For subset sum ("does some subset of these numbers add up to exactly T?"), the certificate is the subset itself: add it up and compare with T, which takes O(n) time. Finding such a subset may be hard; checking one is easy.
The most common misreading: NP does not mean "not polynomial". The name stands for "nondeterministic polynomial time", from an equivalent definition using machines that can guess. Every problem in P is also in NP, because if you can solve a problem quickly you can check a yes answer quickly by solving it. So P is inside NP. The open question is whether NP contains anything outside P.
NP-hard and NP-complete
A problem is NP-hard if every problem in NP can be reduced to it in polynomial time: a fast algorithm for it would give a fast algorithm for everything in NP. A problem is NP-complete if it is NP-hard and itself in NP. The NP-complete problems are therefore the hardest problems in NP, in a precise sense: they are all equally hard up to polynomial factors, and a polynomial-time algorithm for any one of them would put all of NP in P.
NP-hard problems need not be in NP. The optimization version of the traveling salesperson problem is NP-hard, but it is not a yes/no question, so it is not in NP as defined. The halting problem is NP-hard and not even solvable.
Reductions, with one example
A polynomial-time reduction from problem A to problem B is a fast way to transform any instance of A into an instance of B with the same yes/no answer. If B has a fast algorithm, so does A: transform, then solve. Read in the other direction, if A is known to be hard, B must be at least as hard.
Example: the Hamiltonian cycle problem asks whether a graph has a cycle that visits every vertex exactly once. Reduce it to the decision version of traveling salesperson: given a graph with n vertices, build a complete graph on the same vertices where an edge costs 1 if it was in the original graph and 2 if it was not. The original graph has a Hamiltonian cycle exactly when the new one has a tour of total cost at most n, because a tour of cost n must use only cost-1 edges. Building the new graph takes O(n^2) time. Since Hamiltonian cycle is NP-complete, this shows the traveling salesperson decision problem is NP-hard; it is also in NP (the certificate is the tour), so it is NP-complete.
SAT, the first NP-complete problem
To start the chain of reductions, someone had to show directly that one problem is NP-complete. The Boolean satisfiability problem (SAT) asks whether there is a true/false assignment to the variables of a logical formula that makes the whole formula true. Stephen Cook proved SAT NP-complete in his 1971 paper "The complexity of theorem-proving procedures", and Leonid Levin proved an equivalent result independently, which is why it is called the Cook-Levin theorem. In 1972 Richard Karp's paper "Reducibility among combinatorial problems" used reductions from SAT to show that 21 well-known problems are NP-complete, which established how widespread the class is. Other standard members include subset sum, the decision version of traveling salesperson, graph coloring with three colors, and Hamiltonian cycle.
P vs NP is unsolved
Whether P equals NP is an open problem. No one has found a polynomial-time algorithm for any NP-complete problem, and no one has proved that none exists. Most researchers expect that P is not equal to NP, but expectation is not proof, and proving lower bounds on algorithms has turned out to be extremely hard. The question is one of the seven Millennium Prize Problems set by the Clay Mathematics Institute.
Being NP-complete means a problem is as hard as anything in NP, in the worst case. If P is not equal to NP, no polynomial-time algorithm solves every instance of it. It does not mean:
- that every instance is hard (many instances of NP-complete problems are easy);
- that the problem cannot be solved (exponential-time algorithms solve it exactly, and small instances finish quickly);
- that no good approximate answer exists (for some NP-hard problems, provably good approximations are fast; for others, even approximation is hard).
Finding versus checking, in code
Examples use Python 3.10 or later and only the standard library. The first function tries subsets of a 10-number list, smallest first, and counts how many it tried. The second checks a proposed answer, given as a list of indices.
from itertools import combinations
def subset_sum_brute(numbers, target):
tried = 0
for size in range(len(numbers) + 1):
for subset in combinations(numbers, size):
tried += 1
if sum(subset) == target:
return subset, tried
return None, tried
def check_certificate(numbers, target, indices):
if len(set(indices)) != len(indices):
return False
if any(i < 0 or i >= len(numbers) for i in indices):
return False
return sum(numbers[i] for i in indices) == target
numbers = [34, 4, 12, 5, 2, 19, 27, 8, 41, 15]
print(subset_sum_brute(numbers, 100))
print(subset_sum_brute(numbers, 1000))
print(check_certificate(numbers, 100, [0, 1, 4, 5, 8]))
print(check_certificate(numbers, 100, [0, 6, 8]))
Output:
((34, 4, 2, 19, 41), 425)
(None, 1024)
True
False
Finding a subset that sums to 100 took 425 tries. When no subset works, as for a target of 1000 (the ten numbers add up to only 167), the search has to try all 2^10 = 1024 subsets before it can say no, and each try adds up to n numbers, so the brute force is O(2^n x n). Each extra number doubles the work. The checker, given a candidate, does one pass over at most n indices: O(n). That gap between finding and checking is what NP captures.
One subtlety: subset sum has a dynamic programming algorithm that runs in O(n x T) time, where T is the target. That is not polynomial in the input size, because T can be written with only about log2 T bits, so O(n x T) can be exponential in the length of the input. Such algorithms are called pseudo-polynomial; the 0/1 knapsack analysis in the DP time complexity guide explains the idea. They are fast when the numbers are small, which is often enough in practice.
What to do when your problem is NP-hard
- Check whether n is small. Exponential search is fine for 20 items. Backtracking with pruning often handles much more than brute force, though its worst case stays exponential.
- Look for a special case. Your inputs may have structure the general problem lacks. 2-SAT (every clause has two literals) is in P even though SAT is NP-complete; many graph problems become easy on trees; subset sum with small numbers yields to the pseudo-polynomial DP.
- Use an approximation algorithm. Some NP-hard optimization problems have fast algorithms with a proven guarantee. For traveling salesperson with distances that obey the triangle inequality, a tour built by walking a minimum spanning tree is at most twice the optimal length.
- Use a heuristic. Greedy construction, local search and similar methods often find good answers quickly, with no guarantee. Measure them on your own data.
- Use a solver. Problems can often be encoded for a SAT or integer programming solver, which uses clever search to handle many practical instances, again without a polynomial guarantee for every input.
To see how fast exponential growth outruns polynomial growth, the Big O Complexity Analyzer evaluates 2^n beside n^2 and n^3: at n = 10, 2^n is 1,024 against n^3 at 1,000, and at n = 1000 it is about 1.07 x 10^301 against 1,000,000,000.
Check yourself
- Is the problem "is this list sorted?" in NP? (Yes. It is in P, and P is inside NP. NP is not the "hard" class.)
- If someone found an O(n^3) algorithm for subset sum, polynomial in the input size, what would follow? (Subset sum is NP-complete, so every problem in NP would be solvable in polynomial time: P = NP.)