Complexity Classes
Complexity Classes
An algorithm being possible is the cheap part — the previous lesson settled that. The expensive part is how the cost grows. Complexity theory sorts decision problems into classes by the resources (time, space, randomness) a machine needs, and then asks which classes are equal. Almost every interesting equality is open — including the one () that a million-dollar prize rides on. We build the map carefully, because the quantum class will have to find its place on it.
Learning Objectives
By the end of this lesson you will be able to:
- Use asymptotic notation () precisely and state the definitions.
- Formalize a computational problem as a decision problem / language and explain why this loses no generality.
- Define , , , , and via the Turing-machine model, and state the standard inclusions.
- Define polynomial-time reductions and NP-completeness, and explain the role of SAT / 3-SAT (Cook–Levin).
- State clearly what is known and what is open (notably ), and locate the question "where does quantum fit?" relative to these classes.
Intuition
Two problems can both be "solvable" yet live in entirely different universes of practicality. Sorting numbers takes steps — double the input, the work barely more than doubles. Brute-forcing a length- password over an alphabet of size takes — add one character, multiply the work by . The first is polynomial, the second exponential, and that single dichotomy — polynomial vs. exponential — is the coarse but astonishingly durable line between "tractable" and "intractable."
Three resources matter:
- Time — number of steps. The class = polynomial time = "efficient."
- Nondeterminism / verification — can you check a claimed solution fast even if finding it is hard? That is : easy to verify, maybe hard to find.
- Space — memory cells used. allows polynomial memory but possibly exponential time; you can reuse memory, which is why it contains so much.
A fourth resource, randomness, gives (efficient with coin flips and a bounded error probability). It is the classical benchmark against which quantum's is measured: a quantum speedup only "counts" if it beats randomized classical algorithms, not just deterministic ones.
Hold one picture in mind for the whole lesson — the inclusion chain we will justify:
Almost none of these inclusions is known to be strict, and where sits relative to is a central open question. Quantum lives inside — it is not magic — but is conjectured to escape .
Theory
1. Asymptotic notation (refresher)
We measure cost as a function of input size , ignoring constants and low-order terms. For eventually-nonnegative [Sip §7.1], [AB §0.3]:
| Notation | Definition | Reading |
|---|---|---|
| grows no faster than (upper bound) | ||
| grows at least as fast as (lower bound) | ||
| and | and grow at the same rate | |
| is strictly dominated: | ||
| strictly dominates: |
Useful facts: any polynomial is ; logs beat polynomials beat exponentials, for any ; and are transitive. The "" here is a traditional abuse — "" means "," set membership, not equality.
Why polynomials are the dividing line. Polynomials are closed under addition, multiplication, and composition. That closure is exactly what makes robust: composing two polynomial-time subroutines, or simulating one polynomial model on another with polynomial overhead (the Extended Church–Turing thesis from Lesson 1), keeps you in polynomial time. Exponentials are not so forgiving.
2. Decision problems and languages
A decision problem asks a yes/no question of an input. We encode inputs as strings over and identify the problem with its language — the set of yes-instances:
For example , where denotes a binary encoding. "Deciding " means a TM that halts on every input and accepts exactly (Lesson 1).
This costs no generality. A search problem ("output a satisfying assignment") or optimization problem ("find the largest clique") reduces to polynomially many decision queries by binary search / self-reduction: e.g. ask "is the max clique ?" for each , then fix vertices one at a time. So classifying languages by difficulty classifies all of computation, and lets us use the clean machine-decides-a-language framework.
3. The class P
is the class of problems a deterministic TM solves in polynomial time. By the Extended Church–Turing thesis it is machine-independent: multi-tape TMs, RAM machines, and your laptop all agree on . Examples: sorting, shortest paths, linear programming, and — famously — primality testing (, Agrawal–Kayal–Saxena 2002). is our formal stand-in for "efficiently solvable."
4. The class NP, verifiers, and certificates
("nondeterministic polynomial time") is most cleanly defined by efficient verification [AB §2.1], [Sip §7.3]:
A language iff there is a polynomial and a polynomial-time DTM (the verifier) such that for all ,
The string is a certificate (or witness). The point: finding may be hard, but checking a proposed is polynomial. Equivalently, is what a nondeterministic TM decides in polynomial time — the machine "guesses" and verifies it.
Examples: SAT (does a Boolean formula have a satisfying assignment? — certificate: the assignment); CLIQUE (does a graph have a -clique? — certificate: the vertices); HAMPATH, SUBSET-SUM, integer factoring as a decision problem. Each yes-instance has a short, checkable proof.
Clearly : if you can solve in polynomial time, you can verify by ignoring the certificate and re-solving. The converse — is verifying-easy the same as solving-easy? — is the vs. question.
5. co-NP
is the class of languages whose complements are in : . Where has short proofs of yes, has short proofs of no. TAUTOLOGY ("is this formula true under every assignment?") is the canonical problem: a no-instance has a short certificate (a falsifying assignment), but it is not obvious how to certify yes succinctly. We have , and whether is open (believed false). If then .
6. Reductions and NP-completeness
A polynomial-time many-one reduction from to , written , is a polynomial-time computable map with
Intuition: rewrites a question about into an equivalent question about , cheaply. The payoff is transfer of difficulty: if and , then (run , then the fast algorithm for ). Reductions are transitive.
is NP-hard if every satisfies ("at least as hard as all of "). is NP-complete if it is NP-hard and — the hardest problems inside . The decisive consequence:
If any NP-complete problem is in , then — all of collapses to polynomial time.
Cook–Levin and SAT / 3-SAT
The Cook–Levin theorem [AB §2.3], [Sip §7.4] proves that SAT (satisfiability of Boolean formulas in CNF) is NP-complete: the polynomial-time computation of any verifier on can be encoded as a CNF formula that is satisfiable iff a valid certificate exists. That single theorem bootstraps the entire NP-complete universe — once SAT is complete, you show a new problem is NP-complete by reducing a known complete problem to it: .
3-SAT (CNF with exactly 3 literals per clause) is also NP-complete via a clause-splitting reduction : a long clause is replaced by a chain of 3-literal clauses linked by fresh variables ,
which is satisfiable (by some setting of the ) iff at least one original literal is true. The reduction is polynomial and preserves satisfiability — the template for thousands of NP- completeness proofs (Karp's 21 problems, and onward).
7. Randomized computation: BPP
Allow the machine fair coin flips. (Bounded-error Probabilistic Polynomial time) is the class of for which a polynomial-time probabilistic TM satisfies [AB §7.1]
The constants are not special: by running independently times and taking the majority vote, the error drops to (a Chernoff bound), so any gap bounded away from amplifies to near-certainty with polynomially many repetitions. Thus errors are a non-issue in practice.
trivially (ignore the coins). Whether the inclusion is strict is open; in fact it is widely conjectured that (derandomization, under standard hardness assumptions). is the right classical yardstick for quantum speedup: is the quantum analogue of , and the interesting claim is .
8. Space: PSPACE
problems decidable using polynomial memory, with no time bound. Reusing memory is powerful: contains all of (and ). To see $\mathrm{NP}\subseteq \mathrm{PSPACE}u\in{0,1}^{p(n)}$, running the verifier on each, reusing the same cells — exponential time, but polynomial space. The canonical -complete problem is TQBF (true quantified Boolean formulas, ). The inclusions hold; whether any is strict is open, though is strongly believed.
9. The map, and what is (not) known
Putting it together, with proven and open:
| Inclusion | Status |
|---|---|
| proven ; strictness open (, Clay Millennium Prize) | |
| proven; conjectured equal (derandomization) | |
| proven; conjectured strict (Shor) | |
| proven (a classical machine can sum amplitudes in poly space) | |
| vs. | incomparable as far as anyone knows; is not believed |
Two cultural points worth internalizing. First, almost everything here is open: we cannot even prove , despite overwhelming belief. Second — a common misconception — quantum computers are not believed to solve NP-complete problems efficiently. Grover's algorithm (Term 3.2) gives only a quadratic speedup for unstructured search, , which is provably optimal for the black-box model — far from polynomial. Quantum's exponential wins (Shor) attach to structured problems like factoring that are not known to be NP-complete.
Where does quantum fit? sits between and . The central conjectures are (quantum genuinely helps) and (it does not help on the hardest verification problems). The full development — the definition of , the proof, and the landscape — is Term 3.6 · BQP & Quantum Complexity.
Worked Examples
Example 1 — A reduction: 3-SAT INDEPENDENT-SET
We show the technique of a reduction by transforming a 3-CNF formula into a graph and a target so that is satisfiable iff has an independent set of size (an independent set = vertices, no two adjacent).
Construction. For each clause create a triangle of three vertices, one per literal. Add edges (i) inside each triangle (so an independent set picks literal per clause), and (ii) between any two vertices labeling contradictory literals and (so we never select both a variable and its negation). Set number of clauses.
Correctness. An independent set of size must take exactly one vertex per triangle (it can take at most one, and needs total from triangles) — i.e. one true literal per clause — and the contradiction edges guarantee these choices are consistent, defining a satisfying assignment. Conversely a satisfying assignment picks one true literal per clause, and those vertices form an independent set of size . The map is computable in polynomial time (size ). Hence , so INDEPENDENT-SET is NP-hard; since it is also in (certificate = the vertex set), it is NP-complete.
Example 2 — Verifier vs. solver: factoring's exponential gap
Consider -decision: "given and a bound , does have a prime factor ?" The input size is bits.
- Verification is easy: a certificate is a factor with . Checking is one long division, time — polynomial in . So .
- Naïve solving is exponential: trial-dividing by takes divisions. Doubling the bit length squares the work.
This -to-verify but -to-solve gap is the texture of . Factoring is not believed NP-complete (it is in , and NP-complete problems there would imply ), and — crucially — Shor's quantum algorithm factors in polynomial time, -ish, placing . That is the quantum speedup, on a structured problem, and it is the concrete evidence for .
Hands-on (Python)
Self-contained, dependency-free. A brute-force 3-SAT solver lets us feel the exponential blow-up: its work scales as in the number of variables , while a verifier given an assignment is instant. We also implement the 3-SAT INDEPENDENT-SET reduction from Example 1 and check the two answers agree.
"""Complexity Classes — brute-force SAT + a reduction demo (plain Python)."""
from itertools import product
import time
# A CNF formula is a list of clauses; a clause is a list of literals.
# A literal is a signed int: +i means variable x_i, -i means NOT x_i. (i >= 1)
def satisfies(formula, assignment):
"""VERIFIER: O(size) check that `assignment` (dict var->bool) sat's formula."""
for clause in formula:
if not any(assignment[abs(l)] == (l > 0) for l in clause):
return False # clause unsatisfied -> formula false
return True
def brute_force_sat(formula, n_vars):
"""SOLVER: try all 2**n_vars assignments. Exponential by construction."""
for bits in product((False, True), repeat=n_vars): # 2**n_vars rows
assignment = {i + 1: bits[i] for i in range(n_vars)}
if satisfies(formula, assignment):
return assignment
return None # UNSAT
# A satisfiable 3-CNF: (x1 ∨ x2 ∨ ¬x3) ∧ (¬x1 ∨ x2 ∨ x3) ∧ (x1 ∨ ¬x2 ∨ x3)
phi = [[1, 2, -3], [-1, 2, 3], [1, -2, 3]]
sol = brute_force_sat(phi, n_vars=3)
print("Satisfying assignment:", sol)
print("Verifier agrees:", satisfies(phi, sol))
# Watch the search space double per added variable.
print("\nSearch-space size 2**v as v grows (the exponential wall):")
for v in (10, 15, 20, 22):
# A trivially-UNSAT formula forces examining all 2**v rows.
unsat = [[1], [-1]] # x1 AND NOT x1 -> always UNSAT
t0 = time.perf_counter()
brute_force_sat(unsat, n_vars=v)
dt = time.perf_counter() - t0
print(f" v={v:2d}: 2**v = {2**v:>10,} brute-force time ≈ {dt*1e3:7.1f} ms")
# ---------------------------------------------------------------------------
# Reduction demo: 3-SAT -> INDEPENDENT-SET (Example 1).
# Build the graph, brute-force the independent set, compare to SAT answer.
# ---------------------------------------------------------------------------
def reduce_3sat_to_indset(formula):
"""Return (vertices, edges, k). Vertex = (clause_index, literal)."""
vertices = [(j, lit) for j, clause in enumerate(formula) for lit in clause]
edges = set()
for a in range(len(vertices)):
for b in range(a + 1, len(vertices)):
(cj, la), (ck, lb) = vertices[a], vertices[b]
same_triangle = (cj == ck) # (i) one literal per clause
contradictory = (la == -lb) # (ii) consistency edges
if same_triangle or contradictory:
edges.add((a, b))
return vertices, edges, len(formula) # k = #clauses
def has_independent_set(vertices, edges, k):
"""Brute-force: is there a k-subset with no internal edge?"""
from itertools import combinations
for subset in combinations(range(len(vertices)), k):
s = set(subset)
if not any(a in s and b in s for (a, b) in edges):
return True
return False
V, E, k = reduce_3sat_to_indset(phi)
sat_answer = brute_force_sat(phi, 3) is not None
ind_answer = has_independent_set(V, E, k)
print(f"\nReduction check: SAT={sat_answer}, INDEPENDENT-SET(k={k})={ind_answer}")
assert sat_answer == ind_answer, "Reduction must preserve the yes/no answer!"
print("3-SAT and its reduced INDEPENDENT-SET instance agree. ✓")Expected output (timings are machine-dependent, but the doubling is the lesson):
Satisfying assignment: {1: False, 2: False, 3: False} # the first one found
Verifier agrees: True
Search-space size 2**v as v grows (the exponential wall):
v=10: 2**v = 1,024 brute-force time ≈ 1.0 ms
v=15: 2**v = 32,768 brute-force time ≈ 38.0 ms
v=20: 2**v = 1,048,576 brute-force time ≈ 1340.0 ms
v=22: 2**v = 4,194,304 brute-force time ≈ 5980.0 ms
Reduction check: SAT=True, INDEPENDENT-SET(k=3)=True
3-SAT and its reduced INDEPENDENT-SET instance agree. ✓Each added variable roughly doubles the brute-force time — the exponential wall, live. No known algorithm avoids it in the worst case; whether one exists is .
Exercises
1. (Easy) Asymptotics drill. Rank by growth rate (slowest first) and give the class of each:
Solution
Order: $100n\ (\Theta(n)) \prec n\log_2 n\ (\Theta(n\log n)) \prec 2^{10}n^2\ (\Theta(n^2)) \prec n^{2.5}\ (\Theta(n^{2.5})) \prec 2^{\sqrt n}\ (\text{sub-exponential}) \prec 2^n/n$. Constants (, ) vanish inside . Note beats every polynomial ($\sqrt n,\log 2 = \omega(\log n)2^n/n$.
2. (Easy–Medium) Closure of P. Prove that if and then . Where exactly is closure of polynomials under composition used?
Solution
Let be the reduction, computable in time , and let decide in time . On input of size : compute in ; crucially (a TM writes at most one symbol per step). Then run in . Total , polynomial. Composition is used twice: is polynomial in , and a polynomial of a polynomial () is again polynomial.
3. (Medium) Verifier for CLIQUE. Give a formal verifier for : state the certificate, the check, and its running time, confirming .
Solution
Certificate = a list of vertices, length . Verifier $V(\langle G,k\rangle, u)ukG\binom{k}{2}$ pairs are edges of . Step (ii) is adjacency lookups, polynomial in the input. accepts iff a valid clique is presented, so . Hence .
4. (Medium) coNP certificates. Explain why TAUTOLOGY (every assignment satisfies ) is in but not obviously in . What would a short yes-certificate need to do, and why is that suspicious?
Solution
is in : certificate = a falsifying assignment, checked in polynomial time. Hence $\mathrm{TAUT}\in \mathrm{coNP}\mathrm{TAUT}\in\mathrm{NP}$ we would need a short, poly-checkable proof that is true under all assignments. No such proof system is known; if one existed for all tautologies it would imply , which is believed false. (Indeed is -complete.)
5. (Hard) Self-reducibility. Show that if SAT (the decision problem) is in , then one can find a satisfying assignment in polynomial time. Conclude that the search and decision versions of SAT are polynomially equivalent.
Solution
Suppose a poly-time decider for SAT. Given satisfiable : set and ask . If satisfiable, fix ; else must return satisfiable (since was), so fix . Recurse on the remaining variables. This makes calls to , each on a formula no larger than , so total time is . The constructed assignment satisfies by induction. Thus decision search ; the reverse is trivial. SAT is self-reducible.
6. (Hard) Where quantum is not magic. Grover searches an unstructured space of size in queries, provably optimal in the black-box model. (a) Why does this not put NP-complete problems in ? (b) Contrast with factoring.
Solution
(a) For an NP-complete problem with -bit certificates, treating verification as a black box and "Grovering" over candidates costs — still exponential in , merely a square-root speedup. Polynomial time would require an exponential speedup, which the optimal-query lower bound forbids for unstructured search. So quantum does not collapse into ; is not believed. (b) Factoring is structured: Shor exploits the periodicity of via the quantum Fourier transform to get a genuine polynomial-time algorithm — an exponential speedup that does place . The lesson: quantum exponential speedups need structure; brute force only gets a quadratic discount.
Checkpoint
1. Define $f=\Theta(g)$ and give one $f,g$ with $f=O(g)$ but $f\ne\Theta(g)$.
means and (same growth rate). Example: , has but , so .
2. Why does classifying languages capture all of computation?
Search and optimization problems reduce to polynomially many decision queries via self-reduction / binary search. So the difficulty of languages determines the difficulty of everything.
3. Give the verifier-based definition of $\mathrm{NP}$ in one sentence.
iff there is a poly-time verifier and polynomial such that exactly when some certificate makes .
4. What is the single consequence of one NP-complete problem being in P?
: a polynomial algorithm for any NP-complete problem, composed with the reductions, solves every problem in polynomial time.
5. State the inclusion chain placing $\mathrm{BQP}$, and which links are open.
. All inclusions are proven; is a theorem, while is conjectured (Shor) and vs. is open/incomparable.
6. True or false: quantum computers efficiently solve NP-complete problems. Justify.
False (as far as is known). Grover gives only a quadratic speedup for unstructured search, — still exponential — and that is optimal. Quantum's exponential wins (Shor) are on structured problems like factoring, which is not known to be NP-complete.
Further Reading
- [Sip §7.1–7.4] Sipser — asymptotics, , , NP-completeness, Cook–Levin. The most readable first treatment; the SAT and 3-SAT material here follows it.
- [AB §2, §7] Arora & Barak — rigorous , reductions, Cook–Levin, and error amplification; §0.3 for asymptotic notation.
- [AB §4] Arora & Barak — space complexity and (TQBF completeness).
- [NC §3.2] Nielsen & Chuang — computational complexity classes oriented toward quantum, including and the lead-in to .
- [Aar] Aaronson — sharp intuition for and the (mis)belief that quantum solves NP-complete problems.
← Prev: Models of Computation · Up: Term 0 · Next: Reversible Computation →