TExcelTAD
Home › Advanced & Succinct Data Structures › Models of Computation: Comparisons, Words and Cell Probes

Models of Computation: Comparisons, Words and Cell Probes

A lower bound is a statement about every algorithm, and "every algorithm" only means something once you say what an algorithm is allowed to do. The Ω(nlg⁡n)\Omega(n \lg n) bound for sorting holds for algorithms that only compare keys; radix sort ignores it by looking at digits. Part II uses several models side by side, each with its own cost measure, and a bound is meaningless without its model. This lesson lays them out; the next one studies the word-RAM in detail.

The comparison model

The algorithm may move keys around freely, but it learns about them only by asking "is a<ba < b?". Every such algorithm is a decision tree: each internal node is a comparison, each leaf an output. A tree that distinguishes LL possible answers has height at least ⌈lg⁡L⌉\lceil \lg L \rceil, which gives:

Problem Distinct answers LL Lower bound (comparisons)
sorting nn keys n!n! lg⁡n!=nlg⁡n−nlg⁡e+O(lg⁡n)\lg n! = n \lg n - n \lg e + O(\lg n)
searching for xx among nn sorted keys (predecessor) n+1n + 1 ⌈lg⁡(n+1)⌉\lceil \lg (n+1) \rceil
merging two sorted lists of length nn (2nn)\binom{2n}{n} 2n−O(lg⁡n)2n - O(\lg n)

These bounds are tight within the model (merge sort, binary search, linear merging), and balanced BSTs are optimal comparison-based dictionaries. The program checks the information-theoretic count against merge sort for a few sizes: merge sort uses at most n⌈lg⁡n⌉−2⌈lg⁡n⌉+1n \lceil \lg n \rceil - 2^{\lceil \lg n \rceil} + 1 comparisons, within about 10 percent of ⌈lg⁡n!⌉\lceil \lg n! \rceil.

python · try it yourself
import math

def merge_sort_worst(n):
    """Worst-case comparisons of top-down merge sort: W(n) = W(floor) + W(ceil) + n - 1."""
    if n <= 1:
        return 0
    return merge_sort_worst(n // 2) + merge_sort_worst(n - n // 2) + n - 1

for n in [4, 16, 100, 1000, 10 ** 5]:
    lower = math.ceil(math.lgamma(n + 1) / math.log(2))      # ceil(lg n!)
    w = merge_sort_worst(n)
    print(f"n = {n:6}: lg n! >= {lower:8}  merge sort worst {w:8}  ratio {w / lower:.3f}")
n =      4: lg n! >=        5  merge sort worst        5  ratio 1.000
n =     16: lg n! >=       45  merge sort worst       49  ratio 1.089
n =    100: lg n! >=      525  merge sort worst      573  ratio 1.091
n =   1000: lg n! >=     8530  merge sort worst     8977  ratio 1.052
n = 100000: lg n! >=  1516705  merge sort worst  1568929  ratio 1.034

The word-RAM

Memory is an array of ww-bit words, and in one step the machine can do arithmetic (++, −-, ×\times, division), bitwise operations (AND, OR, XOR, shifts) and comparisons on words, and read or write a word at a computed address. Keys are integers in {0,…,U−1}\{0, \ldots, U - 1\} with U=2wU = 2^w, and w≥lg⁡nw \ge \lg n so that an address fits in a word. This is how real processors work, and because it can use a key as an address or chop it into bit fields, the comparison lower bounds do not apply. Sorting nn words in O(nlg⁡lg⁡n)O(n \sqrt{\lg \lg n}) expected time and predecessor search in O(lg⁡lg⁡U)O(\lg \lg U) are word-RAM results. The Word-RAM Model covers it in detail.

The pointer machine

A weaker model used for persistence and dynamic trees. Memory is a set of nodes, each with a constant number of fields holding either a value or a pointer to another node. The algorithm holds a constant number of pointers into the structure and can follow a pointer, create a node or change a field, each at unit cost. There is no address arithmetic: you cannot jump to "the node at position ii", only walk to it. Balanced BSTs, linked lists and union-find forests are pointer-machine structures; arrays and hash tables are not. Lower bounds on a pointer machine (for example Tarjan's 1979 bound for union-find on a class of pointer machines) say what linked structures can do, and the node-copying method for persistence works precisely for pointer-machine structures with bounded in-degree.

The cell-probe model

The strongest model for lower bounds, introduced by Yao (1981). Memory is an array of cells of ww bits each. An operation's cost is the number of cells it reads or writes; all computation between probes is free, and the algorithm may depend arbitrarily on the cells already read. Since a word-RAM operation reads at most one cell, a cell-probe lower bound is automatically a word-RAM lower bound, for every possible instruction set.

The model is useful because it isolates the one thing a data structure cannot avoid: fetching information. Two landmark results, stated without proof:

  • Partial sums and dynamic connectivity. Pătrașcu and Demaine (2004, 2006) proved that maintaining prefix sums of an array under updates, and maintaining connectivity of a dynamic graph, need Ω(lg⁡n)\Omega(\lg n) cell probes per operation (amortized, for the worse of update and query) with w=Θ(lg⁡n)w = \Theta(\lg n). Earlier, Fredman and Saks (1989) had shown Ω(lg⁡n/lg⁡lg⁡n)\Omega(\lg n / \lg \lg n).
  • Predecessor. Pătrașcu and Thorup (2006) determined the cell-probe complexity of static predecessor search as a function of nn, ww and the space. A consequence: with near-linear space, the better of van Emde Boas trees (about lg⁡w\lg w) and fusion trees (about log⁡wn\log_w n) is optimal up to constant factors over a wide range of parameters.

Upper bounds in the cell-probe model can be surprisingly small. Static membership ("is x∈Sx \in S?") needs only O(1)O(1) probes with O(n)O(n) cells, by the two-level perfect hashing scheme of Fredman, Komlós and Szemerédi (1984). The program builds that scheme with seeded random hash functions and counts the cells a query touches, against binary search on a sorted array.

python · try it yourself
import random

P = (1 << 61) - 1                                      # a Mersenne prime above every key
rng = random.Random(1984)

def draw(m):
    a, b = rng.randrange(1, P), rng.randrange(P)
    return (a, b, m)

def h(f, x):
    a, b, m = f
    return ((a * x + b) % P) % m

def build_fks(keys):
    n = len(keys)
    while True:                                        # level 1: retry until sum of squares <= 4n
        top = draw(n)
        buckets = [[] for _ in range(n)]
        for k in keys:
            buckets[h(top, k)].append(k)
        if sum(len(b) ** 2 for b in buckets) <= 4 * n:
            break
    tables = []
    for b in buckets:                                  # level 2: a collision-free table of size |b|^2
        size = max(1, len(b) ** 2)
        while True:
            f = draw(size)
            slots = [None] * size
            ok = True
            for k in b:
                j = h(f, k)
                if slots[j] is not None:
                    ok = False; break
                slots[j] = k
            if ok:
                break
        tables.append((f, slots))
    return top, tables

def fks_member(s, x):
    top, tables = s
    f, slots = tables[h(top, x)]                       # probe 1: the cell holding (f, table address)
    return slots[h(f, x)] == x, 2                      # probe 2: one slot of the second-level table

keys = list({rng.randrange(10 ** 12) for _ in range(2000)})
keys.sort()
s = build_fks(keys)
space = len(keys) + sum(len(t[1]) for t in s[1])
srt = sorted(keys)

def bs_member(x):
    lo, hi, probes = 0, len(srt), 0
    while lo < hi:
        mid = (lo + hi) // 2; probes += 1
        if srt[mid] < x: lo = mid + 1
        else: hi = mid
    return lo < len(srt) and srt[lo] == x, probes

qs = keys[:500] + [rng.randrange(10 ** 12) for _ in range(500)]
assert all(fks_member(s, q)[0] == bs_member(q)[0] for q in qs)
print("keys:", len(keys), " cells used by FKS:", space, f"({space / len(keys):.2f} per key)")
print("FKS probes per query: always", max(fks_member(s, q)[1] for q in qs))
print("binary search probes per query: up to", max(bs_member(q)[1] for q in qs))
keys: 2000  cells used by FKS: 6615 (3.31 per key)
FKS probes per query: always 2
binary search probes per query: up to 11

Building the table is randomized (expected O(n)O(n) time), but every query afterwards costs exactly two probes in the worst case. This does not contradict the comparison bound: hashing computes an address from the key, which a comparison algorithm cannot do. Dynamic structures are a different story, as the Ω(lg⁡n)\Omega(\lg n) connectivity bound shows.

External memory and caches

Two more cost measures appear in the memory hierarchies section. The external-memory (disk-access, DAM) model has a fast memory of MM words and a slow memory moved in blocks of BB words; the cost is the number of block transfers, and computation is free, much like cell probes with big cells. The cache-oblivious model is the same machine, but the algorithm does not know MM and BB.

Model Unit of cost Typical bound
comparison one comparison search ⌈lg⁡(n+1)⌉\lceil \lg (n+1) \rceil
word-RAM one word operation predecessor O(lg⁡lg⁡U)O(\lg \lg U)
pointer machine one pointer step or field change link-cut tree O(lg⁡n)O(\lg n) amortized
cell probe one cell read or written connectivity Ω(lg⁡n)\Omega(\lg n)
external memory (DAM) one block transfer search Θ(log⁡Bn)\Theta(\log_B n)

Test yourself

Why is a lower bound proved in the cell-probe model also a lower bound for the word-RAM?

  1. Because the cell-probe model has smaller words
  2. Because each word-RAM instruction reads or writes at most a constant number of cells, and the cell-probe model charges nothing for computation
  3. Because both models only allow comparisons
  4. It is not; the models are incomparable

Which structure can **not** be implemented on a pointer machine as defined here?

  1. A red-black tree
  2. A doubly linked list
  3. A hash table indexed by h(k)h(k)
  4. A union-find forest

FKS perfect hashing answers membership with 2 probes, while comparison-based search needs about lg⁡n\lg n. What makes the difference?

  1. FKS uses O(n2)O(n^2) space
  2. FKS computes memory addresses from the key, which comparisons cannot do
  3. FKS is amortized
  4. FKS only works for random keys