Polynomial Time and Encodings
Every problem in this track so far had an efficient algorithm: sorting in , shortest paths in , string matching in . But for some natural problems, finding a shortest tour through cities, scheduling exams without clashes, packing a knapsack, nobody has found an algorithm that is polynomial in the input size, and there is strong evidence that none exists. The theory of NP-completeness explains which problems these are and how they relate. This first lesson makes precise the words it is built on: problem, input size and polynomial time.
Polynomial time as "efficient"
An algorithm runs in polynomial time if its worst-case running time is for some constant , where is the size of the input. The class of problems solvable this way is called P. Equating P with "efficiently solvable" is a convention with good reasons behind it:
- An algorithm is useless in practice, but natural problems in P almost always have algorithms with small exponents, and the first polynomial algorithm for a problem is usually improved quickly.
- Polynomial time is the same for every reasonable model of computation: a RAM, a Turing machine and a real computer simulate each other with polynomial overhead.
- Polynomials are closed under addition, multiplication and composition: a polynomial-time algorithm that calls a polynomial-time subroutine a polynomial number of times, on inputs of polynomial size, is still polynomial. That makes P robust when algorithms are combined.
The contrast is with exponential time. The program shows how quickly leaves even behind, assuming steps per second.
def human(seconds):
for unit, size in [("years", 31_557_600), ("days", 86_400), ("hours", 3600), ("minutes", 60)]:
if seconds >= size:
return f"{seconds / size:.3g} {unit}"
return f"{seconds:.3g} seconds"
print(" n n^3 steps 2^n steps")
for n in [20, 40, 60, 80, 100]:
print(f"{n:4} {human(n ** 3 / 1e9):>16} {human(2 ** n / 1e9):>18}") n n^3 steps 2^n steps
20 8e-06 seconds 0.00105 seconds
40 6.4e-05 seconds 18.3 minutes
60 0.000216 seconds 36.5 years
80 0.000512 seconds 3.83e+07 years
100 0.001 seconds 4.02e+13 years
Abstract problems and decision problems
An abstract problem is a relation between instances and solutions: an instance of SHORTEST-PATH is a graph with two vertices, a solution is a shortest path between them. NP-completeness theory restricts attention to decision problems, whose answer is yes or no: "is there a path from to with at most edges?"
This loses less than it seems. An optimization problem is usually no harder than its decision version up to a polynomial factor: if the decision version can be answered quickly, binary search on finds the optimum value, and often the solution itself can be recovered by asking more questions. Conversely the decision version is no harder than the optimization problem. So to show that an optimization problem is hard, it suffices to show that its decision version is hard.
from collections import deque
def has_path_within(adj, u, v, k):
"""decision problem: is there a u-v path with at most k edges? (BFS)"""
dist = {u: 0}
q = deque([u])
while q:
x = q.popleft()
for y in adj[x]:
if y not in dist:
dist[y] = dist[x] + 1
q.append(y)
return v in dist and dist[v] <= k
adj = {0: [1, 2], 1: [3], 2: [4], 3: [5], 4: [5], 5: [6], 6: [7], 7: []}
lo, hi, questions = 0, len(adj), 0 # optimization by binary search on k
while lo < hi:
mid = (lo + hi) // 2
questions += 1
if has_path_within(adj, 0, 7, mid):
hi = mid
else:
lo = mid + 1
print("shortest path from 0 to 7 has", lo, "edges, found with", questions, "yes/no questions")shortest path from 0 to 7 has 5 edges, found with 3 yes/no questions
Encodings and input size
An algorithm does not see a graph or a number; it sees a string of bits, an encoding of the instance. The input size is the length of that string, and the choice of encoding can change whether an algorithm counts as polynomial.
Take the question "is prime?" decided by trial division up to . If is written in unary (a string of ones), the input size is and the divisions are fewer than the input length: polynomial. In binary the input size is only bits, and divisions is exponential. The same algorithm, two verdicts. The 0/1 knapsack DP of 0/1 Knapsack and Pseudo-Polynomial Time is the same phenomenon: polynomial in the value , exponential in its length.
def trial_division_steps(N):
d, steps = 2, 0
while d * d <= N:
steps += 1
if N % d == 0:
return steps
d += 1
return steps
print(" N steps unary length binary length")
for N in [101, 10007, 1000003, 100000007]:
s = trial_division_steps(N) # all four are prime: the worst case
print(f"{N:11} {s:7} {N:14} {N.bit_length():15}") N steps unary length binary length
101 9 101 7
10007 99 10007 14
1000003 999 1000003 20
100000007 9999 100000007 27
To avoid such artifacts, the theory uses reasonable encodings: numbers in binary (or any base at least 2), graphs as adjacency lists or matrices, sets as lists of their elements. Any two reasonable encodings are polynomially related: each can be converted to the other in polynomial time, and their lengths differ by at most a polynomial factor. For example, a graph with vertices and edges takes bits as an adjacency matrix and bits as an edge list, and each is computed from the other in polynomial time. Whether a problem is in P does not depend on which reasonable encoding is used. Unary numbers are not reasonable in this sense, because they are exponentially longer than binary ones.
Languages
The formal version identifies a decision problem with the set of encodings of its yes-instances, a language . An algorithm decides in polynomial time if, for every string , it answers whether in time . Then
Strings that are not valid encodings are simply no-instances; checking validity takes polynomial time for reasonable encodings, so this convention changes nothing. The language view makes later definitions short: NP, reductions and completeness are all statements about languages.
Test yourself
Which statement about the class P is true?
- P contains only problems with algorithms
- P is closed under composition: a polynomial algorithm calling a polynomial subroutine polynomially often is polynomial
- Whether a problem is in P depends on the programming language
- Every problem in P is solved in practice in linear time
Trial division tests a number given in binary with about divisions. In terms of the input length this is
- about , exponential
Why does NP-completeness theory restrict attention to decision problems?
- Optimization problems cannot be encoded
- Decision versions are usually as hard as the optimization problem up to a polynomial factor, and yes/no answers make the theory simpler
- Decision problems are always easier
- Optimization problems are never in P
Which encoding is NOT reasonable in the sense of the theory?
- A graph as an adjacency matrix
- A graph as an edge list
- A number in unary
- A number in base 16