Sub topic 5
NP: Problems Whose Answers We Can Check Efficiently
This chapter assumes you already know four things from earlier chapters. A decision problem is a question whose answer for each input is yes or no. P is the class of decision problems solvable in polynomial time. A certificate is a piece of evidence that supports a yes answer. A verifier is an algorithm that checks that evidence. Here we turn those ideas into a precise definition of the class NP, look at what the definition does and does not say, and go through the mistakes people make most often when using it.
The Formal Definition
A decision problem L is in NP if there is a polynomial p and an algorithm V, called the verifier, with these properties:
- V takes two inputs: an instance x and a candidate certificate c.
- V runs in time polynomial in the length of x.
- Completeness: if x is a yes-instance, then some certificate c with |c| ≤ p(|x|) makes V(x, c) accept.
- Soundness: if x is a no-instance, then V(x, c) rejects for every c.
Put briefly, x is a yes-instance exactly when a short certificate exists that V accepts.
Each clause does real work:
- "Short certificate" means the certificate's length is bounded by a polynomial in the input size. Without this bound you could hand the verifier an exponentially long table of answers, and "checking" would stop meaning anything.
- "Polynomial-time verifier" is measured against |x|. Because the certificate is polynomially bounded, polynomial in |x| and polynomial in |x| + |c| come to the same thing.
- "For every c" in the soundness condition is what stops cheating. No certificate, however cleverly built, may fool V on a no-instance.
A Verifier for 3-Coloring
A graph is 3-colorable if you can give each vertex one of three colors so that no edge joins two vertices of the same color. An earlier chapter showed that 2-coloring is in P. For three colors, no polynomial-time algorithm is known. Checking a proposed coloring is still easy, and that is all NP membership needs.
from itertools import product
def verify_3_coloring(vertices, edges, coloring):
"""coloring: dict mapping each vertex to a color in {0, 1, 2}."""
# The certificate must color exactly the graph's vertices.
if set(coloring) != set(vertices):
return False
# Every color must be one of the three allowed values.
if any(c not in (0, 1, 2) for c in coloring.values()):
return False
# No edge may join two vertices of the same color.
return all(coloring[u] != coloring[v] for u, v in edges)
def is_3_colorable_brute_force(vertices, edges):
"""Decides 3-coloring by running the verifier on all 3^n certificates."""
vertices = list(vertices)
for colors in product((0, 1, 2), repeat=len(vertices)):
if verify_3_coloring(vertices, edges, dict(zip(vertices, colors))):
return True
return False
triangle_v = ["a", "b", "c"]
triangle_e = [("a", "b"), ("b", "c"), ("a", "c")]
print(verify_3_coloring(triangle_v, triangle_e, {"a": 0, "b": 1, "c": 2})) # True
print(verify_3_coloring(triangle_v, triangle_e, {"a": 0, "b": 0, "c": 2})) # False
k4_v = [1, 2, 3, 4]
k4_e = [(u, v) for u in k4_v for v in k4_v if u < v]
print(is_3_colorable_brute_force(triangle_v, triangle_e)) # True
print(is_3_colorable_brute_force(k4_v, k4_e)) # FalseThe verifier runs in O(V + E) time, and the certificate has one entry per vertex, so both bounds in the definition are met. The two input checks at the top are part of soundness. A verifier that skipped them could accept a "coloring" that leaves a vertex out or uses a fourth color.
What the Brute-Force Function Tells Us
The function is_3_colorable_brute_force decides the problem by trying every certificate. Any NP problem can be handled the same way. If certificates have at most p(n) bits, there are at most 2^(p(n)+1) of them, and each check takes polynomial time. So:
- NP ⊆ EXP: every NP problem can be solved in exponential time.
- The open question is whether that exponential search can always be avoided. Brute force shows that NP problems are decidable. It says nothing about whether they are efficiently decidable.
P Is Inside NP
Every problem in P is also in NP. If an algorithm A decides L in polynomial time, define a verifier that ignores the certificate and runs A. The empty certificate is enough for every yes-instance. 2-coloring, shortest path with a length bound, and primality testing are therefore all in NP. Whether the inclusion is strict, P ≠ NP, is the central open question of the tutorial and gets its own chapter later.
Examples
| Problem | Question | Certificate | Verification cost |
|---|---|---|---|
| 3-Coloring | Can G be colored with 3 colors? | A color for each vertex | O(V + E) |
| Subset Sum | Does some subset of the numbers sum to t? | A set of indices | O(n) additions |
| SAT | Does some assignment satisfy formula φ? | A truth assignment | O(size of φ) |
| Hamiltonian Cycle | Does G have a cycle visiting every vertex once? | An ordering of the vertices | O(V + E) |
| Composite | Is integer N not prime? | A factor d with 1 < d < N | One division, polynomial in the bit length of N |
| 2-Coloring | Can G be colored with 2 colors? | None needed (also in P) | O(V + E) |
Common Errors
Reading "NP" as "Non-Polynomial"
NP stands for nondeterministic polynomial time, a name that comes from the machine-based definition in the next chapter. It does not mean "cannot be solved in polynomial time". Every problem in P is in NP, and nobody has proved that any NP problem lies outside P.
Forgetting That the Definition Is One-Sided
Certificates prove only yes answers. For 3-coloring, a valid coloring is convincing evidence. For "this graph is not 3-colorable", no short certificate is known. Swapping yes and no gives the class co-NP, which is not known to equal NP. When you claim a problem is in NP, first make sure you have framed it so that the answer with the short evidence is "yes".
Measuring Size by Value Instead of Bits
Input size is the number of bits needed to write the input down. The integer N takes about log₂ N bits. A verifier for Composite that tries every divisor up to N runs in time exponential in the input size, even though the number of steps looks "linear" in N. A certificate check must be polynomial in the bit length. The chapter on pseudo-polynomial time comes back to this trap.
Accepting Certificates That Are Too Long
Suppose the certificate for "does this game position have a winning strategy?" is the whole game tree. Checking it may be easy relative to its own size, but the tree can be exponentially large in the board description. That violates the length bound, so it does not show the problem is in NP.
Writing an Unsound Verifier
A verifier must reject every bad certificate, including malformed ones: indices out of range, duplicate entries, missing vertices. A verifier that crashes or accepts on garbage input breaks the soundness condition. Treat the certificate as untrusted input.
Exercises
Exercise
The Clique problem asks whether graph G has k vertices that are all pairwise adjacent. Describe a certificate and verifier that show Clique is in NP, and state the verifier's running time.
Show answer
The certificate is a list of k vertices. The verifier checks that the list has exactly k distinct vertices of G, then checks every pair for an edge. With an adjacency set, that costs O(k^2) lookups, which is polynomial because k ≤ V. The certificate has at most V entries, so its length is polynomial.
Exercise
A student says "Primality is in P, so it cannot be in NP, because NP problems are the ones without fast algorithms." What is wrong with this?
Show answer
NP means nondeterministic polynomial time, not non-polynomial. Every problem in P is in NP: the verifier can ignore the certificate and run the polynomial-time algorithm, for example AKS for primality. So primality is in both P and NP.
Exercise
Someone proposes this certificate for "graph G is not 3-colorable": a list of all 3^n colorings, each paired with an edge it violates. Why does this not show the problem is in NP?
Show answer
The certificate has 3^n entries, which is exponential in the input size, so it breaks the requirement that the certificate length be bounded by a polynomial. No polynomial-size certificate for non-3-colorability is known. The problem is in co-NP, and it is not known to be in NP.
Exercise
Modify verify3coloring into verifykcoloring(vertices, edges, coloring, k). Is the k-Coloring problem, with k given as part of the input, in NP?
Show answer
Replace the color check with "if any(not isinstance(c, int) or c < 0 or c >= k for c in coloring.values()): return False" and keep the rest. The certificate still has one color per vertex. Each color fits in O(log k) bits, so the certificate length is polynomial, and the checks take O(V + E) time. So k-Coloring is in NP.