TExcelTAD
Home › Foundations of Algorithm Analysis › Problems, Instances and Input Size

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 nn numbers a0,a1,…,an−1a_0, a_1, \ldots, a_{n-1}.
  • Output: a permutation b0,…,bn−1b_0, \ldots, b_{n-1} of the input with b0≤b1≤⋯≤bn−1b_0 \le b_1 \le \cdots \le b_{n-1}.

An instance of the problem is one particular input, such as ⟨8,3,8,1⟩\langle 8, 3, 8, 1 \rangle. Its correct output is ⟨1,3,8,8⟩\langle 1, 3, 8, 8 \rangle. 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".

python · try it yourself
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.

python · try it yourself
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 nn. What nn 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 nn
Multiplying two integers the total number of bits of the two numbers
Graph problems two numbers: vertices VV and edges EE
Matrix multiplication the dimension nn of the n×nn \times n 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 nn word-sized numbers takes nn words. A single integer NN takes only about lg⁡N\lg N bits. This distinction has real consequences.

When the value is not the size

Consider testing whether an integer NN is prime by trying every divisor from 2 to N\sqrt{N}. The number of trial divisions grows like N\sqrt{N}, which sounds modest. But the input is one number written in about b=lg⁡Nb = \lg N bits, so N=2b/2\sqrt{N} = 2^{b/2}: the work is exponential in the input size. Each extra bit multiplies the worst-case work by about 2\sqrt{2}.

python · try it yourself
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:

cpp · try it yourself
#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 24/22^{4/2}, as predicted. A 2048-bit RSA modulus would need around 210242^{1024} 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 V+EV + E; writing that as "O(n)O(n)" would hide whether nn means vertices or edges, and a dense graph has about V2V^2 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 nlg⁡nn \lg n comparisons for nn 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?

  1. A problem is a hard instance
  2. A problem states the input-output relation in general; an instance is one particular input
  3. An instance is an algorithm for the problem
  4. 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?

  1. Yes, because most lists contain a non-negative number
  2. Yes, because it always halts
  3. No, because correctness requires the right output on every instance, and it fails on all-negative lists
  4. No, because it uses a loop

Trial division tests about N\sqrt{N} divisors. Measured in the input size b≈lg⁡Nb \approx \lg N bits, how does that work grow?

  1. Like bb
  2. Like b2b^2
  3. Like 2b/22^{b/2}, exponentially
  4. Like lg⁡b\lg b

Why is the running time of graph algorithms usually stated with both VV and EE?

  1. Because EE is always V2V^2
  2. Because the number of edges can range from about VV to about V2V^2, so one number would hide the real cost
  3. Because graphs cannot be stored in memory
  4. It is only a convention with no effect