Sub topic 3
P: Problems We Can Solve Efficiently
This chapter assumes you already know what a decision problem is and why we treat polynomial running time as "efficient". Both ideas were covered in the previous two chapters. You should also be comfortable with Big-O notation, adjacency lists, and reading short Python programs.
Here we name the first complexity class, P. We give its formal definition, look at why the definition is more stable than it first appears, and list the mistakes people most often make when they say a problem "is in P".
The Definition
A decision problem can be viewed as a language: the set of input strings whose answer is "yes". An instance of Graph 2-Coloring, for example, is a graph written out as a string of bits. The language contains exactly the strings that encode 2-colorable graphs.
A language L is in P if there is a deterministic algorithm A and a constant k such that:
- A gives the correct yes/no answer for every input string.
- On every input of length n, A halts within O(n^k) steps.
In set notation, P is the union over all k of TIME(n^k). TIME(f(n)) is the class of languages decidable by a deterministic Turing machine in O(f(n)) steps.
The definition has three parts that matter:
- Deterministic. The algorithm makes no guesses, and each step follows from the one before it. The next chapters relax this, and that change is what produces NP.
- Worst case. The bound must hold for every input of length n. Being fast on average or on typical inputs does not qualify.
- Measured in input length. n counts the symbols (bits) needed to write the instance down. It does not count the size of numbers that appear inside the instance.
A Worked Member of P: Graph 2-Coloring
Graph 2-Coloring asks whether you can color every vertex of an undirected graph red or blue so that no edge joins two vertices of the same color. Breadth-first search answers it. Give one vertex color 0, give each of its neighbors the opposite color, and keep spreading outward. If you ever find an edge whose two endpoints have the same color, the answer is no.
from collections import deque
def is_two_colorable(adj):
"""adj: dict mapping each vertex to a list of neighbors (undirected graph)."""
color = {}
for start in adj:
if start in color:
continue
color[start] = 0
queue = deque([start])
while queue:
u = queue.popleft()
for v in adj[u]:
if v not in color:
color[v] = 1 - color[u]
queue.append(v)
elif color[v] == color[u]:
return False
return True
square = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [2, 0]}
triangle = {0: [1, 2], 1: [0, 2], 2: [0, 1]}
print(is_two_colorable(square)) # True: a 4-cycle alternates colors
print(is_two_colorable(triangle)) # False: an odd cycle forces a clashEach vertex enters the queue once and each adjacency entry is read once, so the running time is O(V + E). An adjacency-list encoding of the graph has length at least proportional to V + E, so the algorithm runs in linear time in n. That bound is polynomial, so 2-Coloring is in P.
The outer for start in adj loop matters. Without it, the function would only check the connected component that contains the first vertex, and it would wrongly accept graphs with an odd cycle somewhere else. A correct algorithm has to be correct on every input, including disconnected ones.
Change the problem to three colors and nobody knows a polynomial-time algorithm. 3-Coloring is NP-complete, which a later chapter covers. Problems that look almost the same can fall on opposite sides of this line.
Why the Definition Is Stable
P would be a fragile idea if its membership changed whenever we picked a different computer model or a different input format. It mostly doesn't, for the reasons below.
Machine model
A single-tape Turing machine can simulate a multi-tape machine with at most a quadratic slowdown. A random-access machine with reasonable word sizes can be simulated with a polynomial slowdown as well. A polynomial of a polynomial is still a polynomial, so all of these models define the same class P. The idea that every reasonable deterministic model agrees up to polynomial overhead is sometimes called the Cobham–Edmonds thesis.
Encoding
Adjacency lists and adjacency matrices differ in length by at most a polynomial factor. A matrix uses V² bits, and a list uses about (V + E) log V bits. A polynomial in one length is therefore a polynomial in the other. The one encoding that breaks this is unary numbers, where 5 is written as 11111. Unary can make the input exponentially longer than binary does, which makes slow algorithms look polynomial. Standard practice is to write numbers in binary.
Closure properties
P is closed under several operations, which makes it easy to build new members of P from known ones:
| Operation | Why the result stays in P |
|---|---|
| Complement | Run the decider and flip its answer. |
| Union and intersection | Run both deciders and combine the answers. The total is the sum of two polynomials. |
| Polynomial-time subroutine calls | An algorithm making polynomially many calls to a P subroutine, with polynomially sized inputs, runs in polynomial time. |
| Concatenation | Try each of the n + 1 split points and run both deciders on the two parts. |
The subroutine row is the one you will use most. It is also the core idea behind the reductions in a later chapter.
Some Well-Known Problems in P
| Problem | Algorithm | Running time |
|---|---|---|
| 2-Coloring (bipartiteness) | BFS | O(V + E) |
| Shortest path ≤ k, non-negative weights | Dijkstra with binary heap | O((V + E) log V) |
| 2-SAT | Implication graph and strongly connected components (Aspvall, Plass, Tarjan 1979) | Linear in formula size |
| Perfect matching in a bipartite graph | Hopcroft–Karp | O(E √V) |
| Linear programming feasibility | Ellipsoid (Khachiyan 1979), interior point (Karmarkar 1984) | Polynomial in bit length |
| Primality of an integer N | AKS (2002) | Polynomial in log N |
Primality shows why the bit-length rule matters. Trial division up to √N is "polynomial in N", but the input is only about log N bits long, so √N is exponential in the input size. Primality was only shown to be in P in 2002, when the AKS algorithm achieved running time polynomial in log N.
Common Errors
- Calling an algorithm "in P". P contains problems, not algorithms. You say an algorithm runs in polynomial time, which shows that the problem it solves is in P.
- Equating P with "fast in practice". An O(n^100) algorithm puts a problem in P but is useless in practice. On the other side, the simplex method takes exponential time in the worst case and is still very fast on real linear programs. P is a theoretical boundary. In practice, problems in P usually have algorithms with small exponents, which is why the boundary has proved useful.
- Using average-case or best-case bounds. One family of bad inputs that takes exponential time is enough to break the bound.
- Ignoring the cost of arithmetic. If repeated squaring makes numbers grow to exponentially many bits, counting each multiplication as one step undercounts the real cost.
- Treating "no known polynomial algorithm" as "not in P". For 3-Coloring, SAT, and many other problems, nobody has proved that a polynomial algorithm cannot exist. That open question is P vs NP.
Exercise
An algorithm decides whether a positive integer N (given in binary) is a perfect square by testing every i from 1 to N and checking whether i * i == N. Does this show the problem is in P? If not, describe an approach that does.
Show answer
No. The input has about log N bits, and the loop runs up to N times, which is exponential in log N. Binary search over i in [1, N] needs only O(log N) iterations, and each squaring of an O(log N)-bit number takes polynomial time in log N. That gives a polynomial-time algorithm, so the problem is in P.
Exercise
Suppose problems A and B are both in P. Explain why the problem "Is the input a yes-instance of A but a no-instance of B?" is also in P.
Show answer
Run A's decider, then run B's decider and flip its answer. Accept only if both results are yes. The total time is the sum of two polynomials, which is a polynomial. This uses closure of P under complement and intersection.
Exercise
If you delete the outer "for start in adj" loop from istwocolorable and start BFS only from the first vertex, which input makes the function return the wrong answer?
Show answer
Any disconnected graph where the first vertex's component is bipartite but another component contains an odd cycle. One example is {0: [1], 1: [0], 2: [3, 4], 3: [2, 4], 4: [2, 3]}. BFS from vertex 0 never reaches the triangle on vertices 2, 3, 4, so the function returns True when the correct answer is False.