Sub topic 1
Problems, Instances, and Decision Versions
A reduction turns one problem into another. Before you can build one, you need a precise idea of what a "problem" is. This chapter defines problems, instances, and encodings. It also shows why so much of complexity theory restricts itself to yes/no questions, and when that restriction costs you nothing.
Prerequisites
This chapter assumes you are comfortable with:
- Sets, functions, and basic graph vocabulary (vertices, edges, adjacency).
- Big-O notation and what "polynomial in the input size" means.
- Reading short Python programs that use
itertools. - Boolean formulas such as
(x1 OR NOT x2) AND x3.
You do not need any prior exposure to reductions, NP, or computability.
Problems and Instances
A problem is a general question with parameters left open. An instance is one specific choice of those parameters. "Does graph G have an independent set of size at least k?" is a problem. The path on vertices 0, 1, 2, 3 with k = 2 is one instance of it.
An algorithm solves a problem only if it gives the correct answer on every instance. Being right on the instances you happened to test is not enough. This "every instance" requirement shapes every reduction later in the tutorial. A reduction has to work for all inputs, including the strange ones.
Encoding Instances as Strings
Algorithms read strings, not graphs or formulas. To talk about running time precisely, we fix an encoding: a rule that writes each instance as a finite string over some alphabet, usually binary. The input size is the length of that string.
| Object | Reasonable encoding | Size |
|---|---|---|
| Integer N | Binary digits | about log₂ N bits |
| Graph with n vertices, m edges | Edge list | O((n + m) log n) bits |
| Graph with n vertices | Adjacency matrix | n² bits |
| CNF formula | List of clauses, each a list of literals | O(total literals × log variables) |
Any two reasonable encodings of the same object are polynomially related. An edge list and an adjacency matrix differ in length by at most a polynomial factor, and you can convert one to the other in polynomial time. That means "polynomial time" does not depend on which reasonable encoding you choose.
Decision Problems as Languages
A decision problem is one whose answer on each instance is yes or no. Once instances are strings, a decision problem is the same thing as a language: the set of strings whose answer is yes. Solving the problem means deciding membership in that set.
One detail is easy to miss. Some strings do not encode any instance at all, such as "banana" or a graph that mentions vertex 7 when it has only 3 vertices. The standard convention puts malformed strings outside the language, so the answer is "no". Checking whether a string is well formed is cheap for any reasonable encoding, so this convention never changes the complexity of a problem. It does matter when you write reductions, because a reduction must handle malformed inputs too.
The code below fixes an encoding for the Independent Set decision problem and decides its language by brute force. An independent set is a set of vertices with no edge between any two of them.
from itertools import combinations
def encode(n, edges, k):
edge_part = ",".join(f"{u}-{v}" for u, v in edges)
return f"{n};{edge_part};{k}"
def decode(s):
"""Return (n, edges, k), or None if s is not a well-formed instance."""
parts = s.split(";")
if len(parts) != 3:
return None
try:
n, k = int(parts[0]), int(parts[2])
edges = []
if parts[1]:
for item in parts[1].split(","):
u, v = map(int, item.split("-"))
if not (0 <= u < n and 0 <= v < n) or u == v:
return None
edges.append((u, v))
except ValueError:
return None
if n < 0 or k < 0:
return None
return n, edges, k
def in_independent_set_language(s):
inst = decode(s)
if inst is None:
return False # malformed strings are "no" instances
n, edges, k = inst
for subset in combinations(range(n), k):
chosen = set(subset)
if all(not (u in chosen and v in chosen) for u, v in edges):
return True
return False
path = [(0, 1), (1, 2), (2, 3)]
assert in_independent_set_language(encode(4, path, 2)) # {0, 2}
assert not in_independent_set_language(encode(4, path, 3))
assert not in_independent_set_language("banana")
assert not in_independent_set_language("3;0-5;1") # vertex 5 out of range
print("all checks passed")This decider takes exponential time, because it may examine every k-subset. That is fine here. The point is that the language has an exact definition, so it is clear what any faster algorithm would have to compute.
Search, Optimization, and Decision Versions
Most problems you meet in practice are not yes/no questions. Each one usually comes in several versions:
| Version | Question for Independent Set | Output |
|---|---|---|
| Optimization (value) | What is the largest size of an independent set in G? | A number |
| Optimization (witness) | Find a largest independent set in G. | A vertex set |
| Search | Find an independent set of size at least k, or report none. | A vertex set or "none" |
| Decision | Does G have an independent set of size at least k? | Yes or no |
To get the decision version of an optimization problem, add a threshold k to the input and ask whether some solution beats it. The direction of the inequality follows the goal. For maximization problems (Independent Set, Clique) the question is "at least k". For minimization problems (Vertex Cover, shortest path, traveling salesperson) it is "at most k". If you flip the direction, you usually get a trivial problem. Every graph has an independent set of size at most k, namely the empty set.
Why the Decision Version Is Usually Enough
The decision version is never harder than the others. If you can compute the optimal value, comparing it with k answers the decision question. So a proof that the decision version is hard also shows that every other version is hard.
The surprising part is that the converse usually holds as well, at only polynomial cost. The answer to "is the optimum at least k?" is monotone in k: if it is yes for k, it is yes for every smaller k. Binary search over k therefore recovers the optimal value with about log₂(n + 1) decision queries:
def max_independent_set_size(n, edges):
lo, hi = 0, n # the optimum lies in [lo, hi]
while lo < hi:
mid = (lo + hi + 1) // 2
if in_independent_set_language(encode(n, edges, mid)):
lo = mid
else:
hi = mid - 1
return lo
assert max_independent_set_size(4, [(0, 1), (1, 2), (2, 3)]) == 2For weighted problems, the range of k can be as large as the total weight W. Binary search still needs only O(log W) queries, which is polynomial in the bit length of the weights. A later chapter goes one step further and recovers an actual solution, not just its size, from a yes/no decider.
Edge Cases Worth Fixing in Your Definition
- Thresholds out of range. If k > n, the answer is no. If k = 0, it is yes for every graph. Your definition should still cover these cases without special handling.
- Empty structures. Decide whether a graph with zero vertices, or a formula with zero clauses, is a valid instance. A formula with zero clauses is satisfiable, because nothing constrains it.
- Multigraphs and self-loops. The decoder above rejects self-loops. Another definition could allow them. Either choice is fine, but every reduction you build must respect the one you pick.
- "At least" versus "exactly". "Exactly k" and "at least k" agree for Independent Set, because removing vertices keeps a set independent. For other problems, such as exact-size subgraph problems, they can differ.
Exercise
State the decision version of the shortest path problem on a weighted graph, and explain why asking "is there an s–t path of length at least k?" is the wrong choice.
Show answer
Input: a weighted graph G, vertices s and t, and a number k. Question: is there an s–t path of total weight at most k? Shortest path is a minimization problem, so the threshold has to be an upper bound. "Length at least k" asks something different. On simple paths it becomes the longest path problem, which is NP-hard, while shortest path with nonnegative weights can be solved in polynomial time.
Exercise
An algorithm takes one integer N, written in binary, and runs in O(N) steps. Is it a polynomial-time algorithm?
Show answer
No. The input length is L ≈ log₂ N bits, so O(N) = O(2^L), which is exponential in the input size. An algorithm like this is called pseudo-polynomial.
Exercise
In the worst case, how many calls to inindependentsetlanguage does maxindependentsetsize make on a graph with n vertices? Why is it valid to use binary search?
Show answer
About ⌈log₂(n + 1)⌉ calls, because each call halves the interval [0, n]. Binary search is valid because the yes answers are monotone in k. If G has an independent set of size k, then any subset of it is an independent set of each smaller size.