TExcelTAD
Home › Advanced & Succinct Data Structures › Advanced Data Structures: What Part II Covers

Advanced Data Structures: What Part II Covers

Part I of the Algorithm Theory track built the classic toolkit: hash tables, balanced search trees, B-trees, union-find and the amortized analysis that explains them. Every one of those structures was analysed in one model, the RAM model, and most bounds were of the form O(lg⁡n)O(\lg n) per operation. This course, the first of Part II (Graduate theory), asks three sharper questions.

  1. Is O(lg⁡n)O(\lg n) really the limit? Only for algorithms that learn about keys by comparing them. If keys are integers that fit in a machine word, structures that look at the bits beat lg⁡n\lg n: van Emde Boas trees answer predecessor queries in O(lg⁡lg⁡U)O(\lg \lg U) time, fusion trees in O(log⁡wn)O(\log_w n).
  2. What else can a structure remember or support? Old versions of itself (persistence), changes inserted into the past (retroactivity), a forest that gains and loses edges while answering "are uu and vv connected?" (dynamic connectivity).
  3. What does an operation really cost on a machine with caches and disks, and how little space can a structure use? The external-memory and cache-oblivious models count block transfers instead of instructions; succinct structures use space close to the information-theoretic minimum and still answer queries fast.

The material follows the topics of a graduate advanced data structures course (in the spirit of MIT 6.851) and of the literature on compact data structures. The text, the proofs as sketched here and all programs are written for this site.

How to read the bounds in this course

Graduate-level bounds come with conditions, and the conditions matter as much as the formula. This course always states which kind of bound it means.

Kind Meaning Example
worst case every single operation obeys the bound red-black tree search, O(lg⁡n)O(\lg n)
amortized any sequence of mm operations costs at most mm times the bound; one operation may cost more splay trees and link-cut trees, O(lg⁡n)O(\lg n) amortized
expected averaged over the structure's own random choices, for every input hashing with a universal family, O(1)O(1) expected
with high probability (w.h.p.) fails with probability at most 1/nc1/n^c for a constant cc you may choose skip-list search, O(lg⁡n)O(\lg n) w.h.p.
in a model the cost measure itself: comparisons, word operations, cell probes, block transfers predecessor in O(lg⁡lg⁡U)O(\lg \lg U) on a word-RAM

When a result is quoted from the literature without a proof, the lesson says so and sketches the idea. When a proof is given, it is usually a sketch: the key inequality and why it holds, with the routine algebra left out. Long sketches are inside collapsible "Proof sketch" boxes.

The same question in two models

Here is the first example of how the model changes the answer. The question is predecessor: given a sorted set SS of nn integers from {0,…,U−1}\{0, \ldots, U - 1\} and a query xx, find the largest element of SS that is at most xx. A comparison-based algorithm needs about lg⁡n\lg n comparisons (binary search on the array). A word-RAM structure can instead binary search over the bits of xx: it asks "does some stored key share the top ℓ\ell bits of xx?" with a hash-table lookup and halves the range of ℓ\ell each time, so it needs about lg⁡lg⁡U=lg⁡w\lg \lg U = \lg w lookups, where w=lg⁡Uw = \lg U is the key length. The program counts both for n=214n = 2^{14} keys of w=32w = 32 bits.

python · try it yourself
import random

rng = random.Random(6851)
w = 32
keys = set()
while len(keys) < 2 ** 14:                  # distinct random w-bit keys
    keys.add(rng.randrange(2 ** w))
keys = sorted(keys)

def pred_binary_search(a, x):
    lo, hi, probes = 0, len(a), 0           # invariant: a[:lo] <= x < a[hi:]
    while lo < hi:
        mid = (lo + hi) // 2
        probes += 1
        if a[mid] <= x: lo = mid + 1
        else: hi = mid
    return (a[lo - 1] if lo else None), probes

prefixes = [set() for _ in range(w + 1)]     # prefixes[l] = top l bits of every key
for k in keys:
    for l in range(w + 1):
        prefixes[l].add(k >> (w - l))

def longest_common_prefix(x):
    lo, hi, probes = 0, w, 0                 # some key shares lo bits; none shares more than hi
    while lo < hi:
        mid = (lo + hi + 1) // 2
        probes += 1                          # one hash lookup
        if (x >> (w - mid)) in prefixes[mid]: lo = mid
        else: hi = mid - 1
    return lo, probes

queries = [rng.randrange(2 ** w) for _ in range(1000)]
cmp = [pred_binary_search(keys, q)[1] for q in queries]
lcp = [longest_common_prefix(q) for q in queries]
print("n =", len(keys), " w =", w)
print("comparison model: binary search, max probes", max(cmp), " (lg n =", len(keys).bit_length() - 1, ")")
print("word-RAM: binary search on prefix length, max lookups", max(p for _, p in lcp), " (lg w =", w.bit_length() - 1, ")")
print("typical longest common prefix with a stored key:", sorted(l for l, _ in lcp)[500], "bits")
n = 16384  w = 32
comparison model: binary search, max probes 14  (lg n = 14 )
word-RAM: binary search on prefix length, max lookups 5  (lg w = 5 )
typical longest common prefix with a stored key: 14 bits

Five hash lookups against fourteen comparisons. The longest common prefix is not yet the predecessor, and the prefix tables use nwn w words of space, so this is only the skeleton of the x-fast trie. Turning it into a correct, linear-space structure takes three lessons: x-fast tries, y-fast tries and, before them, van Emde Boas trees, which reach the same O(lg⁡w)O(\lg w) bound by recursion instead of hashing.

Amortized and worst case, side by side

The difference between an amortized and a worst-case bound is easy to say and easy to forget. A dynamic array that doubles when full has O(1)O(1) amortized appends but an occasional append that copies everything (Dynamic Arrays and Doubling). For a real-time system, or for a persistent structure where an expensive operation can be replayed from an old version again and again, that difference decides whether the structure is usable at all. The program shows both numbers.

python · try it yourself
def append_costs(n):
    cap, size, costs = 1, 0, []
    for _ in range(n):
        cost = 1
        if size == cap:
            cost += size                      # copy every element into the new array
            cap *= 2
        size += 1
        costs.append(cost)
    return costs

c = append_costs(1 << 12)
print("appends:", len(c), " total cost:", sum(c), " amortized:", round(sum(c) / len(c), 3))
print("worst single append:", max(c))
# Replaying from an old version: take the state just before a resize and append to it 100 times.
print("100 appends, each from the version of size 2048:", 100 * (2048 + 1))
appends: 4096  total cost: 8191  amortized: 2.0
worst single append: 2049
100 appends, each from the version of size 2048: 204900

The last line is the reason persistence needs care: an amortized analysis assumes each expensive state is passed through once, and a structure that lets you branch from any old version breaks that assumption.

The map of the course

Section Main results Model
Word-RAM and integer structures vEB trees and y-fast tries: predecessor in O(lg⁡lg⁡U)O(\lg \lg U); fusion trees: O(log⁡wn)O(\log_w n); integer sorting in o(nlg⁡n)o(n \lg n) word-RAM
Dynamic connectivity Euler-tour trees and link-cut trees in O(lg⁡n)O(\lg n); fully dynamic graph connectivity in O(lg⁡2n)O(\lg^2 n) amortized updates RAM (pointer machine)
Persistence and retroactivity path copying; node copying with O(1)O(1) amortized overhead; retroactive queues and the Ω(r)\Omega(r) lower bound idea pointer machine
Memory hierarchies sort⁡(N)=Θ(NBlog⁡M/BNB)\operatorname{sort}(N) = \Theta(\frac{N}{B} \log_{M/B} \frac{N}{B}); B-trees optimal for search; cache-oblivious transposition, layout and funnelsort DAM and ideal-cache models
Succinct and probabilistic structures rank and select in o(n)o(n) extra bits; 2n+o(n)2n + o(n)-bit trees; Bloom filters, cuckoo hashing, sketches; suffix arrays and FM-indexes word-RAM, bit counts

The course ends with exercises and a mini project: a persistent key-value store with versions, built on path copying. Later Part II courses build on it: Randomized Algorithms proves the tail bounds behind the "w.h.p." claims, and Streaming, Sketching & Sublinear Algorithms develops the sketches met here.

Note: Every program in this course counts operations (comparisons, lookups, block transfers, bits), never seconds. Counts are exactly reproducible in the browser and say what the theory says; timings in a WebAssembly Python say mostly how fast the interpreter is.

Test yourself

A structure has O(lg⁡n)O(\lg n) **amortized** cost per operation. Which statement is guaranteed?

  1. Every operation takes O(lg⁡n)O(\lg n) time
  2. Any sequence of mm operations takes O(mlg⁡n)O(m \lg n) time in total
  3. The expected time of each operation is O(lg⁡n)O(\lg n)
  4. The time is O(lg⁡n)O(\lg n) with probability 1−1/n1 - 1/n

Why can a word-RAM predecessor structure beat the Ω(lg⁡n)\Omega(\lg n) comparison bound?

  1. It uses more memory than nn words
  2. It reads and manipulates the bits of keys (prefixes, hashing) instead of only comparing keys
  3. It only works for random keys
  4. It is amortized

In the first program, binary search over prefix lengths needs about lg⁡w\lg w lookups. With w=64w = 64-bit keys, about how many is that?

  1. 6
  2. 8
  3. 32
  4. 64