TExcelTAD

Polynomial Time and Encodings

Every problem in this track so far had an efficient algorithm: sorting in O(nlg⁡n)O(n \lg n), shortest paths in O(Elg⁡V)O(E \lg V), string matching in O(n+m)O(n + m). 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 O(nk)O(n^k) for some constant kk, where nn 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 Θ(n100)\Theta(n^{100}) 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 2n2^n leaves even n3n^3 behind, assuming 10910^9 steps per second.

python · try it yourself
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 uu to vv with at most kk 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 kk 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.

python · try it yourself
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 NN prime?" decided by trial division up to N\sqrt{N}. If NN is written in unary (a string of NN ones), the input size is NN and the N\sqrt{N} divisions are fewer than the input length: polynomial. In binary the input size is only β=⌊lg⁡N⌋+1\beta = \lfloor \lg N \rfloor + 1 bits, and N≈2β/2\sqrt{N} \approx 2^{\beta/2} 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 WW, exponential in its length.

python · try it yourself
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 VV vertices and EE edges takes Θ(V2)\Theta(V^2) bits as an adjacency matrix and Θ((V+E)lg⁡V)\Theta((V + E) \lg V) 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 L⊆{0,1}∗L \subseteq \{0, 1\}^*. An algorithm decides LL in polynomial time if, for every string xx, it answers whether x∈Lx \in L in time O(∣x∣k)O(\lvert x \rvert^k). Then

P={L⊆{0,1}∗:some algorithm decides L in polynomial time}.\mathrm{P} = \{ L \subseteq \{0,1\}^* : \text{some algorithm decides } L \text{ in polynomial time} \}.

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?

  1. P contains only problems with O(n2)O(n^2) algorithms
  2. P is closed under composition: a polynomial algorithm calling a polynomial subroutine polynomially often is polynomial
  3. Whether a problem is in P depends on the programming language
  4. Every problem in P is solved in practice in linear time

Trial division tests a number NN given in binary with about N\sqrt{N} divisions. In terms of the input length β\beta this is

  1. O(β)O(\beta)
  2. O(β2)O(\beta^2)
  3. about 2β/22^{\beta/2}, exponential
  4. O(lg⁡β)O(\lg \beta)

Why does NP-completeness theory restrict attention to decision problems?

  1. Optimization problems cannot be encoded
  2. Decision versions are usually as hard as the optimization problem up to a polynomial factor, and yes/no answers make the theory simpler
  3. Decision problems are always easier
  4. Optimization problems are never in P

Which encoding is NOT reasonable in the sense of the theory?

  1. A graph as an adjacency matrix
  2. A graph as an edge list
  3. A number in unary
  4. A number in base 16