Problems, Instances and Input Size
Before you can say that an algorithm is correct or fast, you need to say what it is supposed to do and what "big" means for its input. This lesson pins down three words the rest of the track uses constantly: problem, instance and input size.
Problems and instances
A computational problem is a relation between inputs and acceptable outputs, stated in general terms. The sorting problem, for example:
- Input: a sequence of numbers .
- Output: a permutation of the input with .
An instance of the problem is one particular input, such as . Its correct output is . The problem is the whole infinite family of instances; an algorithm must handle every member of it.
Some problems allow several correct outputs for one instance. "Find a shortest route from A to B" may have two routes of equal length, and either is a correct answer. That is why a problem is a relation and not a function: the specification says which outputs are acceptable, not which one you must produce.
A convenient way to make a specification precise is to write it as a checker: a function that, given an instance and a proposed output, says whether the output is acceptable. The checker below encodes the sorting specification. Note that it checks both halves, "sorted" and "a permutation of the input".
from collections import Counter
def is_correct_sort(instance, output):
is_sorted = all(output[i] <= output[i + 1] for i in range(len(output) - 1))
is_permutation = Counter(output) == Counter(instance)
return is_sorted and is_permutation
instance = [8, 3, 8, 1]
for proposal in [[1, 3, 8, 8], [1, 3, 8], [1, 1, 3, 8], [8, 8, 3, 1], []]:
print(f"{str(proposal):<14} acceptable: {is_correct_sort(instance, proposal)}")[1, 3, 8, 8] acceptable: True
[1, 3, 8] acceptable: False
[1, 1, 3, 8] acceptable: False
[8, 8, 3, 1] acceptable: False
[] acceptable: False
Correct algorithms
An algorithm is correct for a problem if, for every instance, it halts and produces an acceptable output. Two parts: it must stop, and what it returns must satisfy the specification. An algorithm that is wrong on even one instance is incorrect, however well it does on the others.
That standard is strict on purpose. Here is a "maximum" function that looks fine and passes the obvious tests.
from itertools import product
def sloppy_max(a):
best = 0 # bug: assumes some element is at least 0
for x in a:
if x > best:
best = x
return best
print(sloppy_max([3, 9, 2]), sloppy_max([5]), sloppy_max([0, 7, 7]))
# check every instance with 1 to 3 elements drawn from -2..2
failures = [a for n in range(1, 4) for a in product(range(-2, 3), repeat=n)
if sloppy_max(list(a)) != max(a)]
print(len(failures), "failing instances out of", 5 + 25 + 125)
print("smallest:", failures[0])9 5 7
14 failing instances out of 155
smallest: (-2,)
Exhaustive checking of all small instances is a good habit: many bugs already show on inputs of size 1, 2 or 3. It is still not a proof, because the problem has infinitely many instances. The Loop Invariants and Induction lessons give the tools that cover all of them.
Note: Incorrect algorithms are not always worthless. Later in the track you will meet approximation algorithms, whose outputs are within a guaranteed factor of the best, and Monte Carlo algorithms, which are wrong with a small, controlled probability. They are analysed honestly as what they are; they are not called "correct".
Input size
Running times are stated as functions of the input size, written . What measures depends on the problem, and choosing it well is part of the analysis.
| Problem | Natural measure of input size |
|---|---|
| Sorting, searching, summing a list | the number of items |
| Multiplying two integers | the total number of bits of the two numbers |
| Graph problems | two numbers: vertices and edges |
| Matrix multiplication | the dimension of the matrices |
| String matching | the lengths of the text and the pattern |
The common thread: input size is about how much space it takes to write the input down. A list of word-sized numbers takes words. A single integer takes only about bits. This distinction has real consequences.
When the value is not the size
Consider testing whether an integer is prime by trying every divisor from 2 to . The number of trial divisions grows like , which sounds modest. But the input is one number written in about bits, so : the work is exponential in the input size. Each extra bit multiplies the worst-case work by about .
def trial_divisions(N):
d, count = 2, 0
while d * d <= N:
count += 1
if N % d == 0:
return count
d += 1
return count
def is_prime(N):
d = 2
while d * d <= N and N % d:
d += 1
return N >= 2 and d * d > N
for b in [10, 16, 20, 24, 28]:
N = (1 << b) - 1
while not is_prime(N): # the largest prime below 2^b
N -= 1
print(f"b = {b} bits, N = {N:>11,}: {trial_divisions(N):>6,} trial divisions")b = 10 bits, N = 1,021: 30 trial divisions
b = 16 bits, N = 65,521: 254 trial divisions
b = 20 bits, N = 1,048,573: 1,022 trial divisions
b = 24 bits, N = 16,777,213: 4,094 trial divisions
b = 28 bits, N = 268,435,399: 16,382 trial divisions
In C++
The same experiment in C++, with 64-bit long long integers, makes the same trial divisions:
#include <cstdio>
#include <string>
std::string commas(long long n) {
std::string s = std::to_string(n);
for (int i = (int)s.size() - 3; i > 0; i -= 3) s.insert(i, ",");
return s;
}
long long trial_divisions(long long N) {
long long count = 0;
for (long long d = 2; d * d <= N; d++) {
count++;
if (N % d == 0) return count;
}
return count;
}
bool is_prime(long long N) {
long long d = 2;
while (d * d <= N && N % d != 0) d++;
return N >= 2 && d * d > N;
}
int main() {
for (int b : {10, 16, 20, 24, 28}) {
long long N = (1LL << b) - 1;
while (!is_prime(N)) N--; // the largest prime below 2^b
std::printf("b = %d bits, N = %11s: %6s trial divisions\n",
b, commas(N).c_str(), commas(trial_divisions(N)).c_str());
}
}b = 10 bits, N = 1,021: 30 trial divisions
b = 16 bits, N = 65,521: 254 trial divisions
b = 20 bits, N = 1,048,573: 1,022 trial divisions
b = 24 bits, N = 16,777,213: 4,094 trial divisions
b = 28 bits, N = 268,435,399: 16,382 trial divisions
Every 4 extra bits multiply the work by about 4, which is , as predicted. A 2048-bit RSA modulus would need around divisions, far beyond any computer. An algorithm whose running time is polynomial in the numeric value but exponential in the length of the input is called pseudo-polynomial; the knapsack algorithm of the DSA course is another example, because its table has one column per unit of capacity.
Choosing the right measure
When the cost depends on more than one quantity, keep them separate. Breadth-first search on a graph does work proportional to ; writing that as "" would hide whether means vertices or edges, and a dense graph has about edges. Likewise, string matching is analysed in terms of both the text length and the pattern length.
A good rule: pick the measure that makes the statement both true and informative. "Sorting takes about comparisons for items" is useful. "Sorting takes time polynomial in the number of bits" is true but tells you far less.
Test yourself
What is the difference between a problem and an instance?
- A problem is a hard instance
- A problem states the input-output relation in general; an instance is one particular input
- An instance is an algorithm for the problem
- There is no difference
sloppy_max returns the right answer on every list that contains a non-negative number. Is it a correct algorithm for the maximum problem?
- Yes, because most lists contain a non-negative number
- Yes, because it always halts
- No, because correctness requires the right output on every instance, and it fails on all-negative lists
- No, because it uses a loop
Trial division tests about divisors. Measured in the input size bits, how does that work grow?
- Like
- Like
- Like , exponentially
- Like
Why is the running time of graph algorithms usually stated with both and ?
- Because is always
- Because the number of edges can range from about to about , so one number would hide the real cost
- Because graphs cannot be stored in memory
- It is only a convention with no effect