P, NP, NP-Complete and NP-Hard
Some problems can be solved quickly, some can only be checked quickly, and some are at least as hard as everything that can be checked. These four classes sort problems by that difference.
The Four Classes in One Line Each
- P – decision problems a deterministic algorithm solves in polynomial time, O(n^k).
- NP – decision problems whose yes-answers a deterministic algorithm verifies in polynomial time, given a certificate.
- NP-hard – problems that every NP problem reduces to in polynomial time. They need not be in NP.
- NP-complete – problems that are both in NP and NP-hard. The hardest problems inside NP.
The four classes of P, NP, NP-complete and NP-hard sort problems by one question: how does the running time grow with the input size n? An algorithm is efficient when its worst case is a polynomial, such as n, n log n or n³. Anything like 2ⁿ or n! is not.
The classes are defined over decision problems, whose answer is yes or no. "Is there a route shorter than 50 km?" is a decision problem. "Find the shortest route" is its optimisation version. The decision version is never harder, so hardness proven for it carries over to the optimisation version.
NP does not mean "not polynomial". It stands for nondeterministic polynomial: a machine that could guess the right answer would only need polynomial time to check that guess. That checking view is the one used everywhere in practice.
- Any polynomial counts – an n¹⁰⁰ algorithm is still in P, even though nobody could run it
- Pseudo-polynomial is not polynomial – O(n·W) for knapsack grows with the value W, which takes only about log W bits to write down
- NP-hard problems can lie outside NP – even undecidable ones like the halting problem
Certificates: Why Checking Is Easier Than Solving
- Input – the instance, for example a graph G and a number k.
- Certificate – the claimed solution, for example k vertex names.
- Verifier – a polynomial-time check that the certificate really is a solution.
- Membership in NP – every yes-instance has at least one certificate the verifier accepts.
A certificate (or witness) is a proposed solution handed to a verifier. For Independent Set — "does graph G have k vertices with no edge between any two of them?" — the certificate is the list of k vertices.
The verifier only has to check the edges. That is O(V + E) work, polynomial, so Independent Set is in NP. Finding such a set is another matter: the obvious method tries every k-subset, and there are C(n, k) of them, exponential when k grows with n.
Every problem in P is also in NP. If you can solve a problem in polynomial time, you can verify a claimed yes-answer by ignoring the certificate and solving it. So P ⊆ NP is proven. Whether the containment is strict is the P vs NP question, open since 1971 and one of the Clay Millennium Prize problems.
- Only yes-answers need a certificate – problems whose no-answers have short proofs form co-NP; "this formula has no satisfying assignment" has no known short proof
- In NP does not mean hard – "is n composite?" has a factor as its certificate, yet primality testing was shown to be in P (AKS, 2002)
- P = NP would mean every fast check has a fast search behind it
Polynomial-Time Reductions and How to Prove NP-Completeness
- Show B ∈ NP – describe a certificate and a polynomial-time verifier.
- Pick a known NP-complete A – 3-SAT, Vertex Cover, Independent Set, Clique, Subset Sum.
- Build the reduction f – convert any instance of A into an instance of B in polynomial time.
- Prove both directions – yes for A implies yes for B, and yes for B implies yes for A.
A polynomial-time reduction from problem A to problem B, written A ≤p B, is a polynomial algorithm that converts any instance x of A into an instance f(x) of B with the same answer: x is a yes-instance of A exactly when f(x) is a yes-instance of B.
Read the direction carefully, because it is the most common exam mistake. A ≤p B says B is at least as hard as A. A fast algorithm for B would give a fast algorithm for A: convert, then run B's algorithm. To prove a new problem hard, reduce a known hard problem to it.
The chain starts with the Cook–Levin theorem (1971), which proved SAT NP-complete directly, by encoding any polynomial-time verifier as a Boolean formula. Every later proof is a reduction from a problem already on the list, which is why Karp could add 21 problems in 1972 using reductions alone.
- Reductions chain – A ≤p B and B ≤p C give A ≤p C, which is how each new proof builds on the last
- The wrong direction proves little – reducing your new problem to SAT only shows it is no harder than SAT
- Step 1 alone gives NP; steps 2–4 alone give NP-hard
Terms, operations, and practical uses
Core vocabulary
- Decision problemA problem whose answer is yes or no. The classes are defined on these.
- CertificateA proposed solution that a verifier checks in polynomial time.
- Polynomial-time reductionA ≤p B: a polynomial conversion of A's instances into B's with the same answer.
- Cook–Levin theoremSAT is NP-complete — the first problem proven so, and the root of every later reduction.
Proof checklist
- MembershipName the certificate and bound the verifier's running time.
- Source problemReduce from a problem already known to be NP-complete.
- DirectionKnown ≤p new. The reverse direction proves nothing about hardness.
- Both implicationsYes maps to yes, and a yes for the new instance maps back to yes.
Related lessons
- Time and space complexityWhat polynomial and exponential growth mean in operation counts.
- Hamiltonian cycleAn NP-complete graph problem solved by backtracking.
- Branch and boundExact search for NP-hard optimisation, pruned by bounds.
- Graph colouringk-colourability is NP-complete for k ≥ 3.
Code in Python, C++ and Java
from itertools import combinations
VERTICES = "ABCDEF"
EDGES = [("A", "B"), ("A", "C"), ("B", "D"), ("C", "D"), ("C", "E"), ("D", "F"), ("E", "F")]
def is_independent_set(edges, chosen):
# Polynomial verifier: one pass over the edges.
return all(not (u in chosen and v in chosen) for u, v in edges)
def is_vertex_cover(edges, cover):
return all(u in cover or v in cover for u, v in edges)
def independent_set_to_vertex_cover(vertices, k):
# Same graph, new target: an independent set of size k exists exactly
# when a vertex cover of size n - k exists.
return len(vertices) - k
def brute_force_independent_set(vertices, edges, k):
checked = 0
for subset in combinations(vertices, k):
checked += 1
if is_independent_set(edges, set(subset)):
return set(subset), checked
return None, checked
def show(s):
return "{" + ", ".join(sorted(s)) + "}"
good = {"A", "D", "E"}
bad = {"A", "B", "E"}
print("verify {A, D, E}:", str(is_independent_set(EDGES, good)).lower())
print("verify {A, B, E}:", str(is_independent_set(EDGES, bad)).lower())
target = independent_set_to_vertex_cover(VERTICES, 3)
cover = set(VERTICES) - good
print("vertex cover target:", target)
print("cover", show(cover), "valid:", str(is_vertex_cover(EDGES, cover)).lower())
found, checked = brute_force_independent_set(VERTICES, EDGES, 3)
total = len(list(combinations(VERTICES, 3)))
print("brute force found", show(found), "after", checked, "of", total, "subsets")#include <iostream>
#include <set>
#include <string>
#include <utility>
#include <vector>
using namespace std;
using Edge = pair<char, char>;
const string VERTICES = "ABCDEF";
const vector<Edge> EDGES = {{'A', 'B'}, {'A', 'C'}, {'B', 'D'}, {'C', 'D'},
{'C', 'E'}, {'D', 'F'}, {'E', 'F'}};
// Polynomial verifier: one pass over the edges.
bool isIndependentSet(const set<char>& chosen) {
for (const auto& [u, v] : EDGES) {
if (chosen.count(u) && chosen.count(v)) return false;
}
return true;
}
bool isVertexCover(const set<char>& cover) {
for (const auto& [u, v] : EDGES) {
if (!cover.count(u) && !cover.count(v)) return false;
}
return true;
}
// Same graph, new target: an independent set of size k exists exactly when a
// vertex cover of size n - k exists.
int independentSetToVertexCover(int n, int k) { return n - k; }
string show(const set<char>& s) {
string out = "{";
for (char c : s) out += (out.size() > 1 ? ", " : "") + string(1, c);
return out + "}";
}
int main() {
set<char> good = {'A', 'D', 'E'};
set<char> bad = {'A', 'B', 'E'};
cout << boolalpha;
cout << "verify {A, D, E}: " << isIndependentSet(good) << "\n";
cout << "verify {A, B, E}: " << isIndependentSet(bad) << "\n";
set<char> cover;
for (char v : VERTICES) {
if (!good.count(v)) cover.insert(v);
}
cout << "vertex cover target: " << independentSetToVertexCover(VERTICES.size(), 3) << "\n";
cout << "cover " << show(cover) << " valid: " << isVertexCover(cover) << "\n";
// Brute force: every 3-subset in lexicographic order.
int n = VERTICES.size(), checked = 0, total = 0;
set<char> found;
for (int a = 0; a < n; a++) {
for (int b = a + 1; b < n; b++) {
for (int c = b + 1; c < n; c++) {
total++;
set<char> s = {VERTICES[a], VERTICES[b], VERTICES[c]};
if (found.empty()) {
checked++;
if (isIndependentSet(s)) found = s;
}
}
}
}
cout << "brute force found " << show(found) << " after " << checked << " of " << total
<< " subsets\n";
}import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class Main {
static final String VERTICES = "ABCDEF";
static final List<char[]> EDGES = List.of(
new char[] {'A', 'B'}, new char[] {'A', 'C'}, new char[] {'B', 'D'},
new char[] {'C', 'D'}, new char[] {'C', 'E'}, new char[] {'D', 'F'},
new char[] {'E', 'F'});
// Polynomial verifier: one pass over the edges.
static boolean isIndependentSet(Set<Character> chosen) {
for (char[] e : EDGES) {
if (chosen.contains(e[0]) && chosen.contains(e[1])) return false;
}
return true;
}
static boolean isVertexCover(Set<Character> cover) {
for (char[] e : EDGES) {
if (!cover.contains(e[0]) && !cover.contains(e[1])) return false;
}
return true;
}
// Same graph, new target: an independent set of size k exists exactly when
// a vertex cover of size n - k exists.
static int independentSetToVertexCover(int n, int k) {
return n - k;
}
static Set<Character> setOf(char... cs) {
Set<Character> s = new TreeSet<>();
for (char c : cs) s.add(c);
return s;
}
static String show(Set<Character> s) {
return s.toString().replace('[', '{').replace(']', '}');
}
public static void main(String[] args) {
Set<Character> good = setOf('A', 'D', 'E');
Set<Character> bad = setOf('A', 'B', 'E');
System.out.println("verify {A, D, E}: " + isIndependentSet(good));
System.out.println("verify {A, B, E}: " + isIndependentSet(bad));
Set<Character> cover = new TreeSet<>();
for (char v : VERTICES.toCharArray()) {
if (!good.contains(v)) cover.add(v);
}
System.out.println("vertex cover target: " + independentSetToVertexCover(VERTICES.length(), 3));
System.out.println("cover " + show(cover) + " valid: " + isVertexCover(cover));
// Brute force: every 3-subset in lexicographic order.
int n = VERTICES.length(), checked = 0, total = 0;
Set<Character> found = null;
for (int a = 0; a < n; a++) {
for (int b = a + 1; b < n; b++) {
for (int c = b + 1; c < n; c++) {
total++;
Set<Character> s = setOf(VERTICES.charAt(a), VERTICES.charAt(b), VERTICES.charAt(c));
if (found == null) {
checked++;
if (isIndependentSet(s)) found = s;
}
}
}
}
System.out.println("brute force found " + show(found) + " after " + checked + " of " + total + " subsets");
}
}Step through it
Running on A–B, A–C, B–D, C–D, C–E, D–F, E–F; k = 3
Worked Example: Clique Is NP-Complete
This is the proof an exam expects, written in the four-step template. The example graph is chosen so the answer is visible: {1, 3, 5} has no edge inside it in G.
- Known NP-complete problem A – Independent Set: does G have k pairwise non-adjacent vertices?
- New problem B – Clique: does a graph have k pairwise adjacent vertices?
- Instance – G on 5 vertices with edges 1–2, 2–3, 3–4, 4–5, 1–4, 2–4, and k = 3.
Step 1, Clique ∈ NP. The certificate is k vertices. The verifier checks that all k(k − 1)/2 pairs are edges, O(k²) lookups in an adjacency matrix. Polynomial.
Step 2, the reduction. Given (G, k), output (Ḡ, k), where Ḡ is the complement of G: the same vertices, with an edge exactly where G has none. Building Ḡ checks all n(n − 1)/2 pairs, O(n²). Polynomial.
Step 3, correctness in both directions. If S is independent in G, no pair in S is an edge of G, so every pair in S is an edge of Ḡ and S is a clique there. Conversely, a clique in Ḡ has every pair joined in Ḡ, so no pair is joined in G, and it is independent in G. The figure shows the same three vertices in both graphs.
Conclusion. Independent Set ≤p Clique and Clique ∈ NP, so Clique is NP-complete.
- The reduction never solves anything – it only rewrites the instance; the answer is still unknown when it finishes
- Vertex Cover falls out the same way – S is independent exactly when V − S touches every edge; the step-by-step demo runs this one
- Write both directions – one direction alone loses marks
How the Four Classes Relate
The difference between NP-hard and NP-complete comes down to one test: is the problem in NP? Both are at least as hard as everything in NP. An NP-complete problem also has fast-checkable yes-answers; an NP-hard one may not, or may not even be a yes/no question.
The diagram at the top shows the picture everyone assumes, P ≠ NP. P sits inside NP. NP-complete is exactly where NP and NP-hard overlap. NP-hard extends beyond NP to problems that are not even verifiable, such as optimisation versions and the halting problem.
If P = NP, the picture collapses: P, NP and NP-complete become one set (apart from the trivial always-yes and always-no problems), because a polynomial algorithm for any NP-complete problem would solve all of NP through reductions. Most researchers believe P ≠ NP, but no proof exists either way.
If P ≠ NP, Ladner's theorem says there are NP-intermediate problems, in NP but neither in P nor NP-complete. Integer factoring and graph isomorphism are the usual candidates, though neither is proven to be one.
| Class | In NP? | Every NP problem reduces to it? | Examples |
|---|---|---|---|
| P | Yes | Only if P = NP | Sorting, shortest path, MST, 2-SAT |
| NP | Yes (by definition) | Not necessarily | Everything in P, plus SAT, factoring |
| NP-complete | Yes | Yes | SAT, 3-SAT, Vertex Cover, Clique, Hamiltonian Cycle |
| NP-hard | Not necessarily | Yes | Every NP-complete problem, TSP optimisation, halting problem |
- Decision and optimisation versions differ – "is there a tour of cost ≤ B?" is NP-complete; "find the cheapest tour" is NP-hard but not in NP
- Why the halting problem is NP-hard – turn a formula into a program that tries every assignment and halts only if one works; it halts exactly when the formula is satisfiable
- One polynomial algorithm for any NP-complete problem proves P = NP
Famous NP-Complete Problems and What to Do With One
- Small inputs – exponential search is fine: backtracking or branch and bound handle dozens of items.
- Special structure – often restores polynomial time: 2-SAT is in P, and Vertex Cover is easy on trees.
- Pseudo-polynomial DP – the 0/1 knapsack DP runs in O(n·W), fast when the numbers are small.
- Approximation – a guaranteed bound: Vertex Cover has a simple 2-approximation.
- Heuristics – local search and similar methods give good answers without guarantees.
Recognising an NP-complete problem is useful, not defeatist: it tells you to stop looking for an exact polynomial algorithm and choose one of the standard escapes instead.
- SAT / 3-SAT – can the Boolean formula be made true? Certificate: a true/false value per variable
- Vertex Cover – do k vertices touch every edge? Certificate: the k vertices
- Hamiltonian Cycle – is there a cycle through every vertex once? Certificate: the vertex order
- TSP (decision) – is there a tour of cost ≤ B? Certificate: the tour
- Subset Sum – does some subset add up to exactly T? Certificate: the subset
- Graph k-colouring (k ≥ 3) – can vertices get k colours with no clash? Certificate: a colour per vertex