Streaming, Sketching and Sublinear Algorithms: What This Course Covers
Classical algorithm analysis assumes the input sits in memory and the algorithm may look at it as often as it likes. Many modern inputs do not fit that picture. A network router sees billions of packets a day and keeps a few megabytes of state; a search engine's query log is read once, in order, by a job that must report the most frequent queries; a graph with a billion edges arrives as a list of edge insertions and deletions. In these settings the scarce resource is memory, and often the algorithm gets one pass over the data. A second family of problems goes further: the input is in memory but so large that even reading it all is too slow, and the algorithm may only query a few positions. Both families are sublinear: sublinear in space for streaming, sublinear in time for property testing.
This course, a Part II course of the track, develops both. It builds directly on Count-Min Sketch and HyperLogLog and Bloom Filters, which introduced two sketches as data structures, and on the probability tools of Randomized Algorithms: Chernoff bounds, Chebyshev's inequality and k-wise independent hashing. Here the emphasis is on the analysis: exact error guarantees with their conditions, the variants that improve them, and the lower bounds that show where no algorithm can go.
The topic order follows the standard references on the subject: S. Muthukrishnan's survey Data Streams: Algorithms and Applications (2005), Cormode and Yi's Small Summaries for Big Data (2020) and Goldreich's lecture notes and book on property testing (2017). Every explanation, program and exercise here is written from scratch, and results are cited by author and year so that you can find the original papers.
A taste in one pass
One pass over 60 000 page views, three small summaries, and the exact answers for comparison. The summaries are Misra-Gries with 9 counters (frequent items), a reservoir sample of 5 views (a uniform sample without knowing the stream's length) and k minimum values, which estimates the number of distinct pages from the 256 smallest hash values.
import heapq, random
from collections import Counter
rng = random.Random(13)
U = 20000
cum, s = [], 0.0
for i in range(U):
s += 1 / (i + 1) ** 1.3
cum.append(s)
stream = rng.choices(range(U), cum_weights=cum, k=60000) # Zipf-like page ids
# 1. Misra-Gries with 9 counters: every page above m/10 views survives
mg = {}
for x in stream:
if x in mg:
mg[x] += 1
elif len(mg) < 9:
mg[x] = 1
else:
for y in list(mg):
mg[y] -= 1
if mg[y] == 0:
del mg[y]
# 2. Reservoir sample of 5
res = []
for t, x in enumerate(stream):
if t < 5:
res.append(x)
else:
j = rng.randrange(t + 1)
if j < 5:
res[j] = x
# 3. k minimum values: distinct count from the 256 smallest hash values
MASK = (1 << 64) - 1
def mix64(x):
x = (x + 0x9E3779B97F4A7C15) & MASK
x = ((x ^ (x >> 30)) * 0xBF58476D1CE4E5B9) & MASK
x = ((x ^ (x >> 27)) * 0x94D049BB133111EB) & MASK
return x ^ (x >> 31)
k, heap, inheap = 256, [], set()
for x in stream:
h = mix64(x)
if h in inheap:
continue
if len(heap) < k:
heapq.heappush(heap, -h)
inheap.add(h)
elif h < -heap[0]:
inheap.discard(-heapq.heappushpop(heap, -h))
inheap.add(h)
kmv = (k - 1) / (-heap[0] / 2 ** 64)
true = Counter(stream)
print(f"stream: {len(stream)} items; exact answers need a table of {len(true)} entries")
print("Misra-Gries candidates:", ", ".join(f"page {x}: >= {c} (true {true[x]})" for x, c in sorted(mg.items())))
print("reservoir sample of 5:", sorted(res))
print(f"distinct pages: exact {len(true)}, KMV estimate from {k} hashes {kmv:.0f} ({kmv / len(true) - 1:+.1%})")stream: 60000 items; exact answers need a table of 4084 entries
Misra-Gries candidates: page 0: >= 11307 (true 15987), page 1: >= 1893 (true 6572)
reservoir sample of 5: [0, 1, 3, 4, 108]
distinct pages: exact 4084, KMV estimate from 256 hashes 4337 (+6.2%)
The three summaries together hold fewer than 300 numbers, against a table of several thousand entries for the exact answers, and the gap grows without bound: their size does not depend on the stream at all. What they give up is exactness. Misra-Gries undercounts by at most for a stream of length , the reservoir is a random sample rather than a statistic, and the distinct-count estimate is off by a few per cent. Each lesson of the course makes such a guarantee precise and proves it, or proves that nothing better is possible.
What the course covers
| Section | Topics | Main results |
|---|---|---|
| Stream models | insertion-only, cash register and turnstile streams; space in bits and words; deterministic vs randomized; approximate counting; reservoir and weighted sampling | exact counting of distinct items needs bits; Morris counting in bits; reservoir sampling is exactly uniform |
| Heavy hitters | Misra-Gries and its merge, Space-Saving, count-min, Count-Sketch, turnstile heavy hitters | additive error with counters, deterministic; and with probability |
| Frequency moments and cardinality | , the AMS sketch, Flajolet-Martin and KMV, HyperLogLog, communication lower bounds | in words; for HyperLogLog; for exact and for |
| Graph streams | semi-streaming, union-find, -sampling, the AGM sketch, cut and spectral sparsifiers | connectivity in words even with deletions (via bits of sketches); cuts with edges |
| Property testing | query complexity, -far, sortedness, monotonicity, linearity (BLR), bipartiteness, sublinear estimation | for sortedness; for linearity; counting components in time independent of |
The Exercises collect problems from every section, and the Mini Project builds a one-pass log analyser that counts distinct users with HyperLogLog, finds top pages with Misra-Gries and Space-Saving and keeps a reservoir sample, and compares every answer with the exact one.
What you should know first
- Randomized algorithms: tail bounds, pairwise and -wise independence, the median trick for boosting success probability (Amplification by Repetition).
- Hashing: universal hashing and the sketches of Advanced Data Structures.
- Graphs: spanning forests, union-find, minimum cuts (Karger's algorithm).
- Linear algebra for two lessons (the AMS sketch as a random projection, spectral sparsifiers): vectors, inner products, the graph Laplacian at the level of a definition.
Conventions
- A stream is of length over the universe (programs use ). Its frequency vector is , with the number of occurrences of (or, in turnstile streams, the sum of its updates).
- Norms: , . Moments: , so is the number of distinct items (with ), in insertion-only streams and .
- Space is counted in words of bits unless a bound says bits; the difference matters for lower bounds and for HyperLogLog. hides polylogarithmic factors.
- An -approximation of a quantity returns with . Additive guarantees, such as , are stated as such.
- Every random choice in a program comes from a generator with a fixed seed, so the printed numbers are exactly what you will see. Hash functions are either with (pairwise independent) or the splitmix64 mixer
mix64(a fixed, well-mixing function used where the analysis assumes an ideal hash). - Pseudocode is in the track's style (How to read pseudocode).
Test yourself
What is the scarce resource in the data stream model?
- Running time per item only
- Memory: the algorithm sees the stream once, in order, and keeps space far smaller than the stream or the universe
- The number of processors
- Disk bandwidth
What distinguishes a property tester from a streaming algorithm?
- Testers are deterministic
- A tester has random access to the input and reads only a small number of positions; a streaming algorithm reads everything once with little memory
- Testers need more memory
- There is no difference
For a stream over the universe , what does the moment count?
- The stream length
- The number of distinct items, those with
- The most frequent item's count
- The sum of squared frequencies