---
title: "NP-Completeness"
book: "University Computer Science — Year 3"
subject: computer-science
language: en
chapter: 17
exercises: 12
source: https://one-course.com/books/computer-science/5/en/chapter/17-np-completeness
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 17 — NP-Completeness

[Chapter 16](https://one-course.com/books/computer-science/5/en/chapter/16-time-and-space-complexity#ch-b3-complexity-classes) defined NP, the problems whose yes-answers have certificates that are quick to check, and left open whether they can all be solved quickly. Nobody knows. What is known is that thousands of problems from scheduling, routing, packing and logic are equally hard: a fast algorithm for any one of them would give fast algorithms for all of NP. This chapter proves the first such result, the Cook–Levin theorem, by turning the run of any nondeterministic machine into a Boolean formula, and then spreads it by reductions, each one a program tested against brute force: satisfiability to 3-SAT, to [independent set](#def-b3-np-completeness-problems), [clique](#def-b3-np-completeness-problems) and vertex cover, to 3-colouring, to subset sum. It ends with what such a proof tells an engineer: which special cases are easy, and why a “polynomial” dynamic program can still be exponential.

**You already know.**

A formula in conjunctive normal form is a conjunction of clauses, each a disjunction of literals; SAT asks whether it has a satisfying assignment, and $k$-SAT is SAT for clauses of at most $k$ literals (Year 1 volume). A strongly connected component of a directed graph is a maximal set of vertices that can all reach one another; the components can be found in linear time, and contracting them leaves a graph with no cycle (Year 1 volume). A vertex cover of a graph is a set of vertices touching every edge (Year 2 volume). Dynamic programming fills a table of answers to subproblems (Year 1 volume). P, NP and verifiers are those of [Chapter 16](https://one-course.com/books/computer-science/5/en/chapter/16-time-and-space-complexity#ch-b3-complexity-classes).

## 17.1 Polynomial reductions

**Definition 17.1 (Polynomial-time reduction, NP-hard, NP-complete).**

A *polynomial-time reduction* from a problem $A$ to a problem $B$ is a [many-one reduction](https://one-course.com/books/computer-science/5/en/chapter/15-turing-machines-and-computability#def-b3-computability-reduction) $f$ computable in polynomial time: $x \in A$ if and only if $f(x) \in B$. We write $A \le_p B$. A problem $B$ is *NP-hard* when $A \le_p B$ for every $A$ in NP, and *NP-complete* when, in addition, $B$ is in NP.

Reductions compose: if $A \le_p B$ and $B \le_p C$, then $A \le_p C$, since a polynomial of a polynomial is a polynomial (the output of the first reduction has polynomial size). And they carry speed one way: if $A \le_p B$ and $B \in \mathrm{P}$, then $A \in \mathrm{P}$. So one [NP-complete](#def-b3-np-completeness-reduction) problem in P would put all of NP in P; and to prove a new problem $B$ [NP-complete](#def-b3-np-completeness-reduction) it suffices to show $B \in \mathrm{NP}$ and $A \le_p B$ for one known [NP-complete](#def-b3-np-completeness-reduction) $A$. The direction matters: the reduction goes *from* the known hard problem *to* the new one. Reducing the new problem to SAT shows only that it is no harder than SAT.

Richard Karp introduced completeness by polynomial-time [many-one reductions](https://one-course.com/books/computer-science/5/en/chapter/15-turing-machines-and-computability#def-b3-computability-reduction) in 1972 and used it to show 21 problems [NP-complete](#def-b3-np-completeness-reduction).

Michael Garey and David Johnson’s book of 1979 lists over 300. All of them rest on a first one.

## 17.2 The Cook–Levin theorem

**Theorem 17.2 (Cook–Levin theorem).**

SAT is [NP-complete](#def-b3-np-completeness-reduction).

Stephen Cook published it in 1971, with a different notion of reduction; Leonid Levin, working independently in the Soviet Union, published an equivalent result for search problems in 1973; the proof with [polynomial-time reductions](#def-b3-np-completeness-reduction) is Karp’s.

**Proof.** SAT is in NP: an assignment is a certificate, checked clause by clause. Let $A$ be in NP, decided by a nondeterministic machine $N$ in time $n^c$ ([Definition 16.3](https://one-course.com/books/computer-science/5/en/chapter/16-time-and-space-complexity#def-b3-complexity-classes-np)). For an input $w$ of length $n$, let $t = n^c$. A run of $N$ on $w$ is a *tableau*: $t + 1$ rows, each a configuration written as $\#\,u\,q\,v\,\#$ with the state $q$ just left of the cell under the head, all padded to the same width $W = O(t)$. Build the formula $\varphi_w$ on the variables $x_{i,j,s}$, “cell $j$ of row $i$ holds symbol $s$”, with four parts.

- Cells: each cell holds exactly one symbol, a clause of all its symbols and a clause $\neg x_{i,j,s} \vee \neg x_{i,j,s'}$ for each pair.
- Start: row 0 is the start configuration on $w$ , one unit clause per cell.
- Accept: some cell of some row holds the accepting state, one clause.
- Windows: every $2 \times 3$ window, three adjacent cells of a row and the three below, is *legal* , that is, occurs in some configuration and one of its successors.

Only one cell per row holds a state, and a step changes only the cells next to it; so if every window is legal, each row is a successor of the one above, and the tableau is an accepting run. Conversely an accepting run fills a tableau whose windows are all legal, once its last configuration is repeated down to the last row: an accepting configuration counts as its own successor, as it does in `cook_levin.py`. So $\varphi_w$ is satisfiable if and only if $N$ accepts $w$. The legal windows form a fixed finite set, depending on $N$ only. The formula has $O(t^2)$ variables and $O(t^2)$ clauses of constant size, and is written in polynomial time. ∎

The window condition says “one of the legal windows is here”, a disjunction of conjunctions. `cook_levin.py` writes it in conjunctive normal form with one new variable $y$ per window and position, a clause “some $y$ is true” and clauses $y \Rightarrow$ each of its six cells. It builds the formula for a three-state machine that guesses where the pair `11` begins in its input, and `dpll.py`, a plain DPLL solver that [Chapter 18](https://one-course.com/books/computer-science/5/en/chapter/18-approximation-and-exact-methods-for-hard-problems#ch-b3-hard-problems) develops, finds the accepting run.

```python
def formula(word, steps):
    width = max(len(word), steps + 1) + 3  # room for the input and for the head
    num = {}

    def x(i, j, s):  # variable "cell j of row i holds symbol s"
        return num.setdefault((i, j, s), len(num) + 1)
    clauses = []
    for i, j in itertools.product(range(steps + 1), range(width)):
        clauses.append([x(i, j, s) for s in SYMBOLS])  # at least one symbol
        clauses += [[-x(i, j, s), -x(i, j, t)]  # at most one
                    for s, t in itertools.combinations(SYMBOLS, 2)]
    start = ("#", "q0", *word, *"_" * (width - len(word) - 3), "#")
    clauses += [[x(0, j, s)] for j, s in enumerate(start)]
    clauses.append([x(i, j, "qa") for i in range(steps + 1) for j in range(width)])
    windows = legal_windows(width)
    for i, j in itertools.product(range(steps), range(width - 2)):
        choice = []
        for top, bottom in windows:  # y means "this legal window is here"
            y = num.setdefault(("w", i, j, top, bottom), len(num) + 1)
            choice.append(y)
            clauses += [[-y, x(i, j + d, top[d])] for d in range(3)]
            clauses += [[-y, x(i + 1, j + d, bottom[d])] for d in range(3)]
        clauses.append(choice)
    return clauses, num, width, len(windows)
```

***Listing 17.1.** The tableau formula: cells, start row, acceptance, windows. code/bachelor-3/17-np-completeness/listings/cook_levin.py*

```
$ python cook_levin.py
input 011, 3 steps: tableau 4 x 7, 193 legal windows
3,091 variables (196 for cells), 18,009 clauses
#  q0 0  1  1  _  # 
#  0  q0 1  1  _  # 
#  0  1  q1 1  _  # 
#  0  1  1  qa _  #
```

***Output 17.1.** The formula for three steps on `011`, and the tableau read from its satisfying assignment: the machine guessed right at the first 1.*

![The tableau of , one configuration per row. The formula forces every 2 × 3 window to be one of the 193 legal ones.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-np-completeness/fig-5d8a65ce8e5d.svg)

*The tableau of [Output 17.1](#out-b3-np-completeness-cook-levin), one configuration per row. The formula forces every $2 \times 3$ window to be one of the 193 legal ones.*

## 17.3 A chain of reductions

Every reduction below is a function in a listing, run on one small formula, and tested on random small formulas by comparing brute force on both sides; the tests generate the formulas with the `hypothesis` library.

**Definition 17.3 (Independent set, clique, Hamiltonian cycle, subset sum problem).**

An *independent set* of a graph is a set of pairwise non-adjacent vertices; a *clique* is a set of pairwise adjacent ones. The [decision problems](https://one-course.com/books/computer-science/5/en/chapter/16-time-and-space-complexity#def-b3-complexity-classes-decision) ask whether one of size $k$ exists. A *Hamiltonian cycle* is a cycle through every vertex exactly once. The *subset sum problem* asks whether some of given positive integers add up to a target $T$.

**Definition 17.4 (Gadget).**

A *gadget* is a small fixed piece of the instance a reduction builds, one per variable or per clause of the formula, whose possible solutions behave like the truth values or the satisfied clauses.

![The reductions of the chapter. Each arrow A B is A _p B; the dashed one is told, not built.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-np-completeness/fig-e6606d9fe1dd.svg)

*The reductions of the chapter. Each arrow $A \to B$ is $A \le_p B$; the dashed one is told, not built.*

### 17.3.1 From SAT to 3-SAT

A clause of one or two literals is padded with new variables taken with both signs, so that the new clauses hold exactly when the old one does; a clause $\ell_1 \vee \cdots \vee \ell_k$ with $k > 3$ becomes a chain $(\ell_1 \vee \ell_2 \vee y_1)(\neg y_1 \vee \ell_3 \vee y_2) \cdots (\neg y_{k-3} \vee \ell_{k-1} \vee \ell_k)$. If some $\ell_i$ is true, set the $y$s before its clause to true and the others to false; if all $\ell_i$ are false, the chain forces $y_1$, then $y_2$, …, and the last clause fails.

```python
def to_3sat(clauses):
    fresh = max(variables(clauses), default=0)
    out = []
    for c in clauses:
        if len(c) == 1:  # (a): all four ways to fill two new variables
            y, z = fresh + 1, fresh + 2
            fresh += 2
            out += [[c[0], s * y, t * z] for s in (1, -1) for t in (1, -1)]
        elif len(c) == 2:  # (a or b): one new variable, both signs
            fresh += 1
            out += [[c[0], c[1], fresh], [c[0], c[1], -fresh]]
        elif len(c) == 3:
            out.append(list(c))
        else:  # a chain: (l1 or l2 or y1)(not y1 or l3 or y2)...(not y or l_k-1 or l_k)
            fresh += 1
            out.append([c[0], c[1], fresh])
            for lit in c[2:-2]:
                out.append([-fresh, lit, fresh + 1])
                fresh += 1
            out.append([-fresh, c[-2], c[-1]])
    return out
```

***Listing 17.2.** SAT to 3-SAT: every clause becomes clauses of exactly three literals. code/bachelor-3/17-np-completeness/listings/reduce_3sat.py*

```
$ python reduce_3sat.py
SAT:   [[1], [-1, 2], [1, -2, 3, -4, 5], [-3, -5]]
3-SAT: [[1, 6, 7], [1, 6, -7], [1, -6, 7], [1, -6, -7], [-1, 2, 8], [-1, 2, -8], [1, -2, 9], [-9, 3, 10], [-10, -4, 5], [-3, -5, 11], [-3, -5, -11]]
4 clauses on 5 variables -> 11 clauses on 11 variables
satisfiable: True True
```

***Output 17.2.** A formula with clauses of one, two, five and two literals, and its 3-SAT version: 11 clauses, 6 new variables.*

So 3-SAT, with clauses of exactly three literals, is [NP-complete](#def-b3-np-completeness-reduction).

### 17.3.2 Independent set, clique, vertex cover

For a 3-CNF formula with $m$ clauses, build one vertex per literal occurrence, join the three vertices of each clause into a triangle, and join every pair of complementary literals $x$ and $\neg x$. Ask for an [independent set](#def-b3-np-completeness-problems) of size $k = m$. It can take at most one vertex per triangle, so it takes exactly one literal per clause, and never two complementary ones: making them true satisfies the formula. Conversely, a satisfying assignment makes one literal per clause true, and those $m$ vertices are independent.

```python
def to_independent_set(clauses):
    vertices = [(j, lit) for j, c in enumerate(clauses) for lit in c]
    edges = []
    for a, b in itertools.combinations(range(len(vertices)), 2):
        (ja, la), (jb, lb) = vertices[a], vertices[b]
        if ja == jb or la == -lb:  # same clause, or contradictory literals
            edges.append((a, b))
    return vertices, edges, len(clauses)


def to_clique(n, edges, k):
    """An independent set of G is a clique of the complement of G."""
    present = set(edges)
    return n, [e for e in itertools.combinations(range(n), 2) if e not in present], k


def to_vertex_cover(n, edges, k):
    """S is independent if and only if the other n - |S| vertices cover every edge."""
    return n, edges, n - k
```

***Listing 17.3.** 3-SAT to [independent set](#def-b3-np-completeness-problems), then to [clique](#def-b3-np-completeness-problems) and to vertex cover. code/bachelor-3/17-np-completeness/listings/reduce_is.py*

```
$ python reduce_is.py
9 vertices, 15 edges, k = 3
vertices: [(0, 1), (0, -2), (0, 3), (1, -1), (1, 2), (1, 3), (2, -1), (2, -2), (2, -3)]
clique instance: k = 3 edges 21 ; vertex cover instance: k = 6
satisfiable = has an independent set of size k: 200 of 200 random formulas
```

***Output 17.3.** Nine vertices for three clauses; the brute-force check agrees on 200 random formulas.*

The other two follow at once. A set is independent in a graph if and only if it is a [clique](#def-b3-np-completeness-problems) in the complement graph. And $S$ is independent if and only if the other vertices cover every edge, so $G$ has an [independent set](#def-b3-np-completeness-problems) of size $k$ if and only if it has a vertex cover of size $n - k$ ([Exercise 17.7](#exo-b3-np-completeness-7)). From vertex cover a longer chain of [gadgets](#def-b3-np-completeness-gadget) reaches [Hamiltonian cycle](#def-b3-np-completeness-problems): each edge becomes a [gadget](#def-b3-np-completeness-gadget) of twelve vertices that a tour crosses in one of three ways, according to which end of the edge is in the cover. It is told here, not built.

### 17.3.3 3-colouring

Three colours, three special vertices T, F and B in a triangle: in any colouring they take the three colours, and their names fix what the colours mean. For each variable, $x$ and $\neg x$ are joined to each other and to B, so one is coloured T and the other F. For each clause $a \vee b \vee c$, an OR [gadget](#def-b3-np-completeness-gadget) takes $a$ and $b$ and gives an output vertex that can be coloured T if and only if $a$ or $b$ is; a second [gadget](#def-b3-np-completeness-gadget) takes that output and $c$; its output is joined to F and B, so it must be T.

![The gadget of one clause a b c: two OR gadgets, six vertices and twelve edges. If a and b are both F, then u_1 and v_1 must be T and B, which leaves F for o_1.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-np-completeness/fig-623857d8e4a8.svg)

*The [gadget](#def-b3-np-completeness-gadget) of one clause $a \vee b \vee c$: two OR [gadgets](#def-b3-np-completeness-gadget), six vertices and twelve edges. If $a$ and $b$ are both F, then $u_1$ and $v_1$ must be T and B, which leaves F for $o_1$.*

```python
def to_colouring(clauses, n):
    edges = [(T, F), (F, B), (B, T)]
    def lit(x):  # the vertex of literal x: 3, 4 for x_1, not x_1; 5, 6 for x_2 ...
        return 3 + 2 * (abs(x) - 1) + (x < 0)
    for i in range(1, n + 1):
        edges += [(lit(i), lit(-i)), (lit(i), B), (lit(-i), B)]
    size = 3 + 2 * n

    def gadget(a, b):  # OR gadget: a triangle u, v, out with u - a and v - b
        nonlocal size
        u, v, out = size, size + 1, size + 2
        size += 3
        edges.extend([(u, a), (v, b), (u, v), (v, out), (out, u)])
        return out
    for a, b, c in clauses:
        out = gadget(gadget(lit(a), lit(b)), lit(c))
        edges.extend([(out, F), (out, B)])  # the clause's output must be T
    return size, edges
```

***Listing 17.4.** 3-SAT to 3-colouring: the palette, a pair per variable, two OR [gadgets](#def-b3-np-completeness-gadget) per clause. code/bachelor-3/17-np-completeness/listings/reduce_col.py*

```
$ python reduce_col.py
n = 3 variables, m = 2 clauses: 21 vertices, 36 edges
  2n + 6m + 3 = 21, 3n + 12m + 3 = 36
satisfiable = 3-colourable: 30 of 30 random formulas (0 unsatisfiable)
all 8 clauses on x1, x2, x3: satisfiable False, 3-colourable False
```

***Output 17.4.** The sizes match $2n + 6m + 3$ vertices and $3n + 12m + 3$ edges, and the eight clauses that forbid every assignment give a graph with no 3-colouring.*

[Exercise 17.10](#exo-b3-np-completeness-10) proves the reduction correct.

### 17.3.4 Subset sum

Numbers can simulate clauses too, if their digits never carry. For $n$ variables and $m$ clauses, write numbers of $n + m$ decimal digits. For each variable $x_i$, two numbers $y_i$ and $z_i$ have a 1 in digit $i$; $y_i$ also has a 1 in the digit of each clause containing $x_i$, and $z_i$ in each clause containing $\neg x_i$. Each clause also gets two slack numbers with a 1 in its digit. The target has a 1 in each variable digit and a 3 in each clause digit. A digit sums to at most $3 + 2 = 5$, so nothing carries. Reaching a 1 in digit $i$ means choosing exactly one of $y_i$, $z_i$: an assignment. Reaching 3 in a clause digit needs at least one true literal, since the slacks give at most 2.

```python
def to_subset_sum(clauses, n):
    m = len(clauses)

    def number(var_digit, clause_digits):  # digits: variables first, then clauses
        digits = [0] * (n + m)
        if var_digit is not None:
            digits[var_digit] = 1
        for j in clause_digits:
            digits[n + j] += 1
        return int("".join(map(str, digits)))
    numbers = []
    for i in range(1, n + 1):
        numbers.append(number(i - 1, [j for j, c in enumerate(clauses) if i in c]))
        numbers.append(number(i - 1, [j for j, c in enumerate(clauses) if -i in c]))
    for j in range(m):
        numbers += [number(None, [j]), number(None, [j])]  # slack: at most 2 more
    target = int("1" * n + "3" * m)
    return numbers, target
```

***Listing 17.5.** 3-SAT to subset sum, digit by digit. code/bachelor-3/17-np-completeness/listings/reduce_ss.py*

```
$ python reduce_ss.py
numbers: [10010, 10001, 1001, 1010, 111, 100, 10, 10, 1, 1]
target:  11133
satisfiable = some subset reaches the target: 200 of 200 random formulas
```

***Output 17.5.** Ten numbers for three variables and two clauses (leading zeros are not shown), and the check on 200 random formulas.*

## 17.4 co-NP

**Definition 17.5 (co-NP).**

*co-NP* is the class of problems whose complement is in NP: those whose no-instances have certificates checkable in polynomial time.

Is a formula a tautology, true under every assignment? A no-answer has a short certificate, a falsifying assignment; a yes-answer seems to need all $2^n$ assignments. Tautology is in [co-NP](#def-b3-np-completeness-conp), and it is [co-NP-complete](#def-b3-np-completeness-reduction), since $\varphi$ is a tautology exactly when $\neg \varphi$ is unsatisfiable. P is inside NP $\cap$ [co-NP](#def-b3-np-completeness-conp), because P is closed under complement. If some [NP-complete](#def-b3-np-completeness-reduction) problem were in [co-NP](#def-b3-np-completeness-conp), then NP would equal [co-NP](#def-b3-np-completeness-conp) ([Exercise 17.12](#exo-b3-np-completeness-12)). Factoring, as the [decision problem](https://one-course.com/books/computer-science/5/en/chapter/16-time-and-space-complexity#def-b3-complexity-classes-decision) “does $N$ have a factor below $k$?”, is in NP $\cap$ [co-NP](#def-b3-np-completeness-conp), since the full factorisation, checked with a primality test, certifies both answers; it is not known to be in P, and if it were [NP-complete](#def-b3-np-completeness-reduction), NP would equal [co-NP](#def-b3-np-completeness-conp).

## 17.5 What a proof of hardness tells an engineer

An NP-completeness proof says that no algorithm is known that is polynomial on every instance, and that finding one would settle P against NP. It does not say that the instances in front of you are hard. Three ways out are common: a special case that is easy, an algorithm polynomial in the numbers rather than their length, and the approximation and exact methods of [Chapter 18](https://one-course.com/books/computer-science/5/en/chapter/18-approximation-and-exact-methods-for-hard-problems#ch-b3-hard-problems).

**Definition 17.6 (2-SAT, implication graph).**

*2-SAT* is SAT for formulas whose clauses have at most two literals. The *implication graph* of such a formula has a vertex per literal and, for each clause $a \vee b$, the edges $\neg a \to b$ and $\neg b \to a$.

**Theorem 17.7 (2-SAT is in P).**

A 2-CNF formula is unsatisfiable if and only if some variable $x$ and its negation $\neg x$ lie in the same strongly connected component of the [implication graph](#def-b3-np-completeness-2sat). This is decided, and a satisfying assignment found, in time linear in the size of the formula.

The edges are implications that every satisfying assignment respects, so a path from $x$ to $\neg x$ and back makes both values impossible. The converse, and the assignment “$x$ is true when its component comes after that of $\neg x$ in topological order”, are [Exercise 17.9](#exo-b3-np-completeness-9). Aspvall, Plass and Tarjan gave this linear-time algorithm in 1979.

```python
def solve(clauses, n):
    comp = components(implication_graph(clauses, n))
    if any(comp[v] == comp[-v] for v in range(1, n + 1)):
        return None
    # x is true when its component comes later in topological order than not x's
    return {v: comp[v] > comp[-v] for v in range(1, n + 1)}
```

***Listing 17.6.** [2-SAT](#def-b3-np-completeness-2sat) from the components, numbered in topological order by Kosaraju’s algorithm. code/bachelor-3/17-np-completeness/listings/two_sat.py*

```
$ python two_sat.py
formula: [(1, 2), (-1, 3), (-2, -3), (2, 4), (-4, -1)]
components: {0: [1, -2, 3], 1: [-4], 2: [4], 3: [-1, 2, -3]}
assignment: {1: False, 2: True, 3: False, 4: True}
with (x1 or not x2) and (not x1 or not x2): None
```

***Output 17.6.** The components of a formula’s [implication graph](#def-b3-np-completeness-2sat), the assignment they give, and an unsatisfiable extension.*

So [2-SAT](#def-b3-np-completeness-2sat) is linear while 3-SAT is [NP-complete](#def-b3-np-completeness-reduction): the boundary between easy and hard can be one literal wide.

**Definition 17.8 (Pseudo-polynomial algorithm, strongly NP-complete).**

An algorithm is *pseudo-polynomial* when its running time is polynomial in the size of the input and in the magnitude of the numbers in it, rather than in their number of digits. A problem with numbers is *strongly NP-complete* when it remains [NP-complete](#def-b3-np-completeness-reduction) even with all its numbers bounded by a polynomial in the input size.

Subset sum has the dynamic program of the Year 1 volume: the set of sums reachable with the first $i$ numbers, for sums up to the target $T$, filled in $O(nT)$ steps. That is polynomial in $T$, but $T$ is written with about $\log_2 T$ bits.

```python
def dp_cells(numbers, target):
    """Decide subset sum; count the (number, sum) cells the table fills."""
    reachable, cells = [True] + [False] * target, 0
    for x in numbers:
        for s in range(target, x - 1, -1):  # downwards: each number used once
            cells += 1
            if reachable[s - x]:
                reachable[s] = True
    return reachable[target], cells
```

***Listing 17.7.** Subset sum by dynamic programming, counting the cells it fills. code/bachelor-3/17-np-completeness/listings/subset_dp.py*

```
$ python subset_dp.py
n = 20 numbers of b bits; target = half their sum
 b   input bits   target T   table cells   found
 4           80         82         1,495   True
 8          160      1,408        25,363   True
12          240     20,675       372,170   True
16          320    375,952     6,767,155   True
```

***Output 17.7.** Four more bits per number multiply the table by about 16 while the input grows by 80 bits: exponential in the input size.*

The reduction from 3-SAT builds targets with $n + m$ digits, so the dynamic program does not contradict NP-completeness. With numbers written in unary, or bounded by a polynomial, subset sum is in P; so, unless P = NP, it is not [strongly NP-complete](#def-b3-np-completeness-pseudo). 3-colouring has no numbers at all, and is [NP-complete](#def-b3-np-completeness-reduction) in the strong sense automatically.

## 17.6 Exercises

**Exercise 17.1 ★.**

A student shows that a new scheduling problem $S$ is [NP-complete](#def-b3-np-completeness-reduction) by writing a [polynomial-time reduction](#def-b3-np-completeness-reduction) from $S$ to SAT. What has been proved, and what reduction is needed instead?

**Solution of Exercise 17.1.**

$S \le_p \mathrm{SAT}$ proves that $S$ is in NP, no harder than SAT; nothing about its hardness. For NP-hardness the reduction must go the other way: from SAT, or another known [NP-complete](#def-b3-np-completeness-reduction) problem, to $S$. With both, $S$ is [NP-complete](#def-b3-np-completeness-reduction).

**Exercise 17.2 ★.**

Apply the chain of [Listing 17.2](#lst-b3-np-completeness-3sat) to the clause $x_1 \vee \neg x_2 \vee x_3 \vee x_4 \vee \neg x_5$. Check by hand that the result is satisfied when $x_4$ is the only true literal of the clause ($x_1$ and $x_3$ false, $x_2$ and $x_5$ true), and say how the new variables are set.

**Solution of Exercise 17.2.**

$(x_1 \vee \neg x_2 \vee y_1)(\neg y_1 \vee x_3 \vee y_2)(\neg y_2 \vee x_4 \vee \neg x_5)$. With $x_1$ and $x_3$ false and $x_2$ and $x_5$ true, $x_4$ is the only true literal: the first clause needs $y_1$ true, the second then needs $y_2$ true, and the third is satisfied by $x_4$ alone. The rule: the $y$s before the clause of the true literal are true, those after are false.

**Exercise 17.3 ★.**

Draw the independent-set graph for $(x_1 \vee x_2 \vee \neg x_3) \wedge (\neg x_1 \vee x_3 \vee x_2)$ and give an [independent set](#def-b3-np-completeness-problems) of size 2 with the assignment it encodes.

**Solution of Exercise 17.3.**

Six vertices: a triangle $x_1, x_2, \neg x_3$ and a triangle $\neg x_1, x_3, x_2$, plus the edges $x_1 - \neg x_1$ and $\neg x_3 - x_3$. The two $x_2$ vertices are not joined, so $\{x_2, x_2'\}$, one per triangle, is independent of size 2: the assignment $x_2$ true, the others arbitrary. Another is $\{x_1, x_3\}$: $x_1$ and $x_3$ true.

**Exercise 17.4 ★.**

Predict the numbers and the target that `to_subset_sum` builds for the single clause $x_1 \vee \neg x_2 \vee x_3$, and give a subset reaching the target.

**Solution of Exercise 17.4.**

Digits $x_1 x_2 x_3 \mid c_1$: $y_1 = 1001$, $z_1 = 1000$, $y_2 = 100$, $z_2 = 101$, $y_3 = 11$, $z_3 = 10$, two slacks $1$ and $1$; target $1113$. For example $y_1 + y_2 + y_3 + 1 = 1001 + 100 + 11 + 1 = 1113$: all three variables true; the clause digit gets 1 from $y_1$, 1 from $y_3$ and 1 from a slack.

**Exercise 17.5 ★★.**

`exercises/ex5_clique.py` has a reduction from 3-SAT to [clique](#def-b3-np-completeness-problems) that joins every two literals that are not complementary. Find a formula on which it answers wrongly and fix it.

**Solution of Exercise 17.5.**

Joining literals of the same clause lets a [clique](#def-b3-np-completeness-problems) take two literals from one clause and none from another. The eight clauses that forbid every assignment of $x_1, x_2, x_3$ form an unsatisfiable formula, yet the buggy graph has a [clique](#def-b3-np-completeness-problems) of size 8: the literal $x_1$ occurs in four clauses and $x_2$ in four, and these eight occurrences are pairwise non-complementary, so all joined; a test checks it. The fix joins two occurrences only if they lie in different clauses and are not complementary; then a [clique](#def-b3-np-completeness-problems) of size $m$ takes one literal per clause, consistently.

**Exercise 17.6 ★★.**

Write `colouring_to_sat(n, edges)`, a reduction from 3-colouring to SAT. It is tested against backtracking on random graphs.

**Solution of Exercise 17.6.**

`exercises/ex6_col_to_sat.py`: variables $x_{v,c}$ for 3 colours; per vertex one clause $x_{v,0} \vee x_{v,1} \vee x_{v,2}$ and three clauses $\neg x_{v,a} \vee \neg x_{v,b}$; per edge $uv$ and colour $c$, $\neg x_{u,c} \vee \neg x_{v,c}$. A colouring gives a satisfying assignment and back; $3n$ variables and $4n + 3m$ clauses (`test_exercise_6_colouring_to_sat`).

**Exercise 17.7 ★★.**

Prove that vertex cover is [NP-complete](#def-b3-np-completeness-reduction), from [independent set](#def-b3-np-completeness-problems).

**Solution of Exercise 17.7.**

Vertex cover is in NP: the set is a certificate, checked edge by edge. Facts used: $S$ is independent if and only if $V \setminus S$ covers every edge, since an edge with no end in $V \setminus S$ has both ends in $S$. Map $(G, k)$ to $(G, n - k)$: $G$ has an [independent set](#def-b3-np-completeness-problems) of size $k$ if and only if it has a vertex cover of size $n - k$. The map is computed in linear time, so [independent set](#def-b3-np-completeness-problems) $\le_p$ vertex cover, and vertex cover is [NP-complete](#def-b3-np-completeness-reduction).

**Exercise 17.8 ★★.**

Count the variables and clauses of the formula of [Listing 17.1](#lst-b3-np-completeness-cook-levin) for $t$ steps, width $W$, 7 symbols and $L$ legal windows, and check the counts of [Output 17.1](#out-b3-np-completeness-cook-levin).

**Solution of Exercise 17.8.**

Cell variables: $7(t + 1)W$. Window variables: one per legal window and per position, $t(W - 2)L$. Clauses: per cell, one “at least one” and $\binom{7}{2} = 21$ “at most one”: $22(t + 1)W$; the start row, $W$; acceptance, 1; per window position, $6L + 1$: $t(W - 2)(6L + 1)$. For $t = 3$, $W = 7$, $L = 193$: $196 + 15 \times 193 = 3{,}091$ variables and $616 + 7 + 1 + 15 \times 1{,}159 = 18{,}009$ clauses, as printed (`test_cook_levin_counts_and_windows`).

**Exercise 17.9 ★★.**

Prove [Theorem 17.7](#thm-b3-np-completeness-2sat): if no $x$ shares a component with $\neg x$, the assignment of [Listing 17.6](#lst-b3-np-completeness-2sat) satisfies every clause. (Use the symmetry of the graph: $a \to b$ is an edge if and only if $\neg b \to \neg a$ is.)

**Solution of Exercise 17.9.**

Facts used: the graph is symmetric, $a \to b$ being an edge if and only if $\neg b \to \neg a$ is, so a path from $a$ to $b$ gives one from $\neg b$ to $\neg a$, and the components come in mirror pairs; a satisfying assignment never has a true literal implying a false one along an edge.

If $x$ and $\neg x$ share a component, $x \Rightarrow \neg x$ and $\neg x \Rightarrow x$ along paths, so neither value is possible. Conversely, number the components in a topological order and make $x$ true when its component comes after that of $\neg x$. Suppose a clause $a \vee b$ is false: $a$ and $b$ are false, so the component of $\neg a$ comes after that of $a$, and the same for $b$. The edge $\neg a \to b$ puts $b$’s component at or after $\neg a$’s, and the edge $\neg b \to a$ puts $a$’s at or after $\neg b$’s. Then $a \le \neg a \le b \le \neg b \le a$ in the order, with $a$ strictly before $\neg a$: a contradiction. The algorithm finds the components and their order in linear time (`test_two_sat`).

**Exercise 17.10 ★★★.**

Prove that the 3-colouring reduction is correct: the graph is 3-colourable if and only if the formula is satisfiable.

**Solution of Exercise 17.10.**

Facts used: in a 3-colouring the palette T, F, B takes three different colours, which we name by it; a literal vertex is adjacent to B, so it is T or F, and $x$, $\neg x$ differ.

The OR [gadget](#def-b3-np-completeness-gadget) on inputs $a$, $b$ coloured T or F: if both are F, $u$ and $v$ avoid F, so they are T and B in some order, and the output, adjacent to both, is F. If $a$ is T, colour $u$ F, $v$ B (allowed, since $b$ is T or F) and the output T; if $b$ is T, symmetrically. So the output is F whenever both inputs are F, and it can be T when $a$ or $b$ is T. It is not always T or F: with $a$ T and $b$ F, the colouring $u$ F, $v$ T gives the output B. The first argument holds for any input that is F, literal or not.

If the graph is 3-colourable, read the assignment from the literal vertices. Each clause’s last output is adjacent to F and B, so it is T; then the first output and $c$ are not both F. If $c$ is not T it is F, being a literal, so the first output is not F, and then $a$ and $b$ are not both F: $a$, $b$ or $c$ is T, and the clause is satisfied. Conversely, from a satisfying assignment colour the literals, then each [gadget](#def-b3-np-completeness-gadget) as above with output T whenever possible; the last output of each clause is T, compatible with its edges to F and B. Sizes are linear, so the reduction is polynomial.

**Exercise 17.11 ★★★.**

Prove that subset sum is [NP-complete](#def-b3-np-completeness-reduction), and explain why the dynamic program of [Listing 17.7](#lst-b3-np-completeness-dp) does not show it is in P.

**Solution of Exercise 17.11.**

Subset sum is in NP: the subset is the certificate. The reduction of the chapter is correct. If the formula is satisfiable, take $y_i$ or $z_i$ as $x_i$ is true or false; each variable digit is 1, each clause digit has 1 to 3 from the literals, completed to 3 by slacks. If a subset reaches the target, no digit carries, since a digit’s total is at most 5; each variable digit is 1, so exactly one of $y_i$, $z_i$ is chosen, an assignment; each clause digit is 3 with at most 2 from slacks, so some true literal is in the clause. The numbers have $n + m$ digits, written in polynomial time. The dynamic program takes $O(nT)$ steps, and here $T \approx 10^{n + m}$: exponential in the input size, which is about $(2n + 2m)(n + m)$ digits.

**Exercise 17.12 ★★★.**

Prove that if some [NP-complete](#def-b3-np-completeness-reduction) problem is in [co-NP](#def-b3-np-completeness-conp), then $\mathrm{NP} = \mathrm{co\text{-}NP}$.

**Solution of Exercise 17.12.**

Let $C$ be [NP-complete](#def-b3-np-completeness-reduction) and in [co-NP](#def-b3-np-completeness-conp). For $A$ in NP, $A \le_p C$ by a function $f$; then $\overline{A} \le_p \overline{C}$ by the same $f$, and $\overline{C}$ is in NP, so $\overline{A}$ is in NP: $A$ is in [co-NP](#def-b3-np-completeness-conp). So $\mathrm{NP} \subseteq \mathrm{co\text{-}NP}$. For $B$ in [co-NP](#def-b3-np-completeness-conp), $\overline{B}$ is in NP, hence in [co-NP](#def-b3-np-completeness-conp), so $B$ is in NP: $\mathrm{co\text{-}NP} \subseteq \mathrm{NP}$.

## 17.7 Weekend problem

**Problem 17.1.**

Weekend problem — Timetabling the town’s exams

Brenmoor’s school sets its exams in a few time slots; two exams taken by a common student must not share a slot. Exams are vertices, clashes are edges, slots are colours. This problem shows that three slots make the problem [NP-complete](#def-b3-np-completeness-reduction), with the [gadgets](#def-b3-np-completeness-gadget) of [Listing 17.4](#lst-b3-np-completeness-col), and that two slots do not.

**Part I — The decision problem.**

1. State the timetabling problem with $s$ slots as a [decision problem](https://one-course.com/books/computer-science/5/en/chapter/16-time-and-space-complexity#def-b3-complexity-classes-decision) on graphs.
2. Show it is in NP for every $s$ : what is the certificate, and how long does checking take?
3. Six exams, A to F; clashes AB, BC, CA, CD, DE, EF, FD. How many slots are needed?
4. Why does a triangle of clashes need three slots, whatever the rest of the graph?
5. Why is the optimisation problem “fewest slots” no easier than the [decision problem](https://one-course.com/books/computer-science/5/en/chapter/16-time-and-space-complexity#def-b3-complexity-classes-decision) with $s = 3$ ?

**Part II — The gadgets.**

6. In the palette triangle, why can the names T, F and B be given to the colours after the colouring is found?
7. Why is exactly one of $x$ , $\neg x$ coloured T in any 3-colouring?
8. In an OR [gadget](#def-b3-np-completeness-gadget) , show that if $a$ and $b$ are both F then the output is F.
9. Show that if $a$ is T, the [gadget](#def-b3-np-completeness-gadget) can be coloured with output T, whatever $b$ is.
10. Why must the second output of each clause be T?
11. Why does a clause with three false literals make the graph uncolourable?

**Part III — Sizes.**

12. Count the vertices: $2n + 6m + 3$ .
13. Count the edges: $3n + 12m + 3$ .
14. Check both counts against [Output 17.4](#out-b3-np-completeness-col) .
15. A timetable instance built from a formula with 100 variables and 430 clauses: how many exams and clashes?
16. Why is the reduction computable in polynomial time?
17. What do the counts say about the size of the hard instances 3-colouring inherits from 3-SAT?

**Part IV — Two slots against three.**

18. Show that a graph has a 2-colouring if and only if it has no cycle of odd length.
19. Give a linear-time algorithm for two slots, and say what it returns when there is no timetable.
20. Reduce 2-slot timetabling to [2-SAT](#def-b3-np-completeness-2sat) : one variable per exam.
21. Why does the same idea fail for three slots?
22. The school has 40 exams and three slots. Does NP-completeness mean that its timetable cannot be found?
23. What does a school with too many clashes for three slots learn from a failed search, and what would a certificate of impossibility look like?
24. Sum up: what changes between two slots and three?

**Solution of Problem 17.1.**

**1.** Given a graph and $s$, is there a map from vertices to $\{1, \ldots, s\}$ giving different values to the two ends of every edge?

**2.** The certificate is the timetable; checking looks at every vertex and edge once, $O(n + m)$.

**3.** Three: ABC and DEF are triangles; A, B, C get three slots, D a slot other than C’s, E and F the other two.

**4.** Its three exams pairwise clash, so they need three different slots.

**5.** An algorithm for the fewest slots answers the decision with $s = 3$ by comparing; so the optimisation is [NP-hard](#def-b3-np-completeness-reduction) too.

**6.** The three palette vertices are pairwise adjacent, so they take three different colours; calling those colours T, F and B is just naming them.

**7.** $x$ and $\neg x$ are adjacent to B and to each other, so they take the two colours other than B’s, one each.

**8.** $u$ is adjacent to $a$ (F) and $v$ to $b$ (F), so $u, v \in \{T, B\}$, different from each other; the output is adjacent to both, so it is F.

**9.** Colour $u$ F (its neighbour $a$ is T), $v$ B ($b$ is T or F), the output T.

**10.** It is adjacent to F and B.

**11.** The first [gadget](#def-b3-np-completeness-gadget)’s output is F (question 8), and then the second [gadget](#def-b3-np-completeness-gadget)’s inputs are both F, so its output is F, but it must be T.

**12.** 3 palette vertices, $2n$ literal vertices, 6 per clause.

**13.** 3 palette edges, 3 per variable, 12 per clause: 5 per OR [gadget](#def-b3-np-completeness-gadget) and 2 to F and B.

**14.** $n = 3$, $m = 2$: $6 + 12 + 3 = 21$ and $9 + 24 + 3 = 36$, as printed.

**15.** $200 + 2{,}580 + 3 = 2{,}783$ exams and $300 + 5{,}160 + 3 = 5{,}463$ clashes.

**16.** It writes $O(n + m)$ vertices and edges, each by a fixed rule.

**17.** They are linear: a formula of size $N$ becomes a graph of size $O(N)$, so if 3-SAT needs time $2^{\Omega(N)}$ in the worst case, so does 3-colouring, up to the constant in the exponent.

**18.** In a 2-colouring colours alternate along any walk, so a cycle has even length. Conversely, if there is no odd cycle, colour each component by the parity of the distance from a start vertex; an edge between two vertices of the same parity would close an odd cycle.

**19.** Breadth-first search, colouring each new vertex opposite to its parent; on an edge whose ends have the same colour, stop: the two paths to the start and that edge form an odd closed walk, which contains an odd cycle, the certificate that no timetable exists.

**20.** $x_v$ means “exam $v$ in slot 1”; each clash $uv$ gives $(x_u \vee x_v)$ and $(\neg x_u \vee \neg x_v)$: exactly one of the two in slot 1.

**21.** With three slots a vertex needs more than one Boolean variable, and “different slots” is no longer a conjunction of two-literal clauses: “at least one slot” needs three literals.

**22.** No. It means no known algorithm is fast on every graph; with 40 exams, backtracking or a SAT solver ([Chapter 18](https://one-course.com/books/computer-science/5/en/chapter/18-approximation-and-exact-methods-for-hard-problems#ch-b3-hard-problems)) finds a timetable or proves there is none quickly in practice.

**23.** That a solver found no timetable, which is not a short certificate: proofs of non-colourability can be long, since 3-colouring’s complement is in [co-NP](#def-b3-np-completeness-conp) and not known to be in NP. A small certificate exists in special cases, such as four pairwise clashing exams.

**24.** Two slots: linear time, by breadth-first search or [2-SAT](#def-b3-np-completeness-2sat), with an odd cycle as a short proof of impossibility. Three slots: [NP-complete](#def-b3-np-completeness-reduction) by the [gadgets](#def-b3-np-completeness-gadget), with $2n + 6m + 3$ vertices and $3n + 12m + 3$ edges per formula; solved in practice by search, with no short proof of impossibility known in general.
