Exercises
Fifteen problems covering the whole course: stream models and sampling, heavy hitters, frequency moments and distinct counting, lower bounds, graph streams and property testing. Try each one on paper first. Every problem has a short Answer to check yourself against and a full Solution; several solutions include a program that confirms the result, which you can edit and run.
Tip: For a sketch, write down what one row or one counter estimates, its expectation and its variance, and only then decide how many copies to average and how many averages to take the median of. For a lower bound, ask which communication problem the stream could encode.
| # | Exercise | Practises |
|---|---|---|
| 1 | A reservoir, item by item | reservoir sampling |
| 2 | How many decrement steps? | Misra-Gries |
| 3 | Sizing a count-min sketch | count-min |
| 4 | or ? | count-min vs Count-Sketch |
| 5 | Tug of war by hand | AMS sketch |
| 6 | Counting to a billion | Morris counter |
| 7 | Sizing HyperLogLog | HyperLogLog |
| 8 | Reading a KMV sketch | k minimum values |
| 9 | Exact is hard | communication lower bounds |
| 10 | The right level | -sampling |
| 11 | Cancelling edges | AGM sketch |
| 12 | When does uniform sampling sparsify? | Karger sampling |
| 13 | Testing a huge sorted file | sortedness tester |
| 14 | How many BLR checks? | linearity testing |
| 15 | Space-Saving's smallest counter | Space-Saving |
Exercise 1: A reservoir, item by item
Algorithm R keeps items from a stream of . (a) Item 5 enters the reservoir with probability when it arrives. With what probability does it survive each later step ? (b) Multiply to get the probability that item 5 is in the final reservoir, and compare with the theorem.
Answer
(a) at step . (b) .
Solution
At step the new item is accepted with probability and then replaces a uniformly chosen slot, so a particular member is evicted with probability . The product telescopes: . The result agrees with the theorem of Reservoir Sampling. The program checks the product exactly and by simulation.
from fractions import Fraction
import random
k, m, t0 = 3, 20, 5
survive = Fraction(1)
for t in range(t0 + 1, m + 1):
survive *= 1 - Fraction(1, t) # evicted at step t with probability (k/t)(1/k)
print("P[item 5 in the final reservoir] =", Fraction(k, t0) * survive, " k/m =", Fraction(k, m))
rng = random.Random(1)
hits, runs = 0, 40000
for _ in range(runs):
R = list(range(1, k + 1))
for t in range(k + 1, m + 1):
j = rng.randrange(t)
if j < k:
R[j] = t
hits += t0 in R
print(f"simulation over {runs} runs: {hits / runs:.4f}")P[item 5 in the final reservoir] = 3/20 k/m = 3/20
simulation over 40000 runs: 0.1491
Exercise 2: How many decrement steps?
A Misra-Gries summary with counters reads items. At the end the counters sum to . (a) How many decrement steps happened? (b) What is the largest possible undercount of any item? (c) Compare with the generic bound .
Answer
(a) . (b) 6000. (c) ; the tighter bound is 40% smaller.
Solution
Each decrement step removes exactly units of count (99 counters and the arriving item), and every other step adds one, so and . Each decrement step loses at most one occurrence of any fixed item, hence an undercount of at most 6000 (Misra-Gries). The more the counters still hold, the fewer decrement steps there were.
Exercise 3: Sizing a count-min sketch
You want point estimates within with probability per query, for a stream of items. (a) Give and . (b) How much memory do the counters need with 4-byte counters? (c) How does the answer change if the guarantee must hold for all items of the universe at once?
Answer
(a) , . (b) counters, about 76 KB. (c) , about 228 KB.
Solution
From the theorem of Count-Min in Depth: and . For all items at once, use a union bound with , which only changes to . Counters of 4 bytes suffice because . The memory does not depend on or beyond the logarithm in .
Exercise 4: or ?
A frequency vector over items has one item with frequency and all others with frequency 1. Compute and . With , compare the error guarantees of count-min and of Count-Sketch, and the number of columns each needs.
Answer
, . Count-min: error about with columns. Count-Sketch: error about with columns.
Solution
. Count-min's error bound exceeds the heavy item's own frequency, so it cannot even tell the heavy item from the others reliably. Count-Sketch's bound of about 14 locates it easily, at the price of columns (Count-Sketch). For this flat-tailed vector, the guarantee is worth the extra space.
Exercise 5: Tug of war by hand
Let and with independent uniform signs . Compute and directly from the 8 sign vectors, and compare with and .
Answer
and .
Solution
and , so the formula of the AMS sketch gives . The program enumerates the sign vectors (fully independent signs are in particular 4-wise independent).
from itertools import product
from fractions import Fraction
f = [3, -1, 2]
Z2 = [sum(s * x for s, x in zip(signs, f)) ** 2 for signs in product([1, -1], repeat=3)]
mean = Fraction(sum(Z2), len(Z2))
var = Fraction(sum(z * z for z in Z2), len(Z2)) - mean ** 2
F2, F4 = sum(x * x for x in f), sum(x ** 4 for x in f)
print("values of Z^2:", Z2)
print(f"E[Z^2] = {mean} (F2 = {F2}), Var[Z^2] = {var} (2(F2^2 - F4) = {2 * (F2 * F2 - F4)})")values of Z^2: [16, 0, 36, 4, 4, 36, 0, 16]
E[Z^2] = 14 (F2 = 14), Var[Z^2] = 196 (2(F2^2 - F4) = 196)
Exercise 6: Counting to a billion
A Morris counter counts events. (a) About what value does reach, and how many bits does it need? (b) What is the standard deviation of one estimate ? (c) How many independent copies must be averaged so that Chebyshev guarantees error at most with probability ?
Answer
(a) About , so 5 bits. (b) . (c) .
Solution
(a) , so is close to , and values up to 31 fit in 5 bits. (b) (Space as the Resource). (c) The average of copies has variance below , and Chebyshev gives failure probability below ; requiring this to be at most with gives : 150 counters of 5 bits, 750 bits in total, against the 30 bits of an exact counter. Approximate counting pays off only when many counters are needed and each must be tiny, or when a relative error near 50% is acceptable.
Exercise 7: Sizing HyperLogLog
(a) How many registers does HyperLogLog need for a relative standard error of 1%? Round up to a power of two and give the memory with 6-bit registers. (b) What error does that power of two give? (c) Why does the memory not depend on whether you count or distinct items?
Answer
(a) , so registers, 12 KiB. (b) . (c) A register stores a rank of about , which fits in 6 bits for any up to .
Solution
The standard error is with (HyperLogLog). Solving for gives about , and the next power of two is , with . The memory is bits bits KiB, the same as Redis's implementation. Only the register width grows with , and only like .
Exercise 8: Reading a KMV sketch
A KMV sketch with has, as its largest stored hash value normalized to , . (a) Estimate the number of distinct items. (b) Give the approximate relative standard deviation. (c) Another sketch over a different stream, built with the same hash function, has 300 of the 1024 smallest values of the union in common with the first. What does that estimate?
Answer
(a) . (b) About . (c) The Jaccard similarity of the two sets, about .
Solution
The unbiased KMV estimator is , with relative standard deviation at most (Flajolet-Martin and k Minimum Values). In (c), the smallest values of the union are a uniform sample of the union's distinct items, and the fraction present in both sketches estimates .
Exercise 9: Exact is hard
Show that every randomized one-pass algorithm that computes exactly with probability needs bits. Which communication problem do you reduce from, and how does Bob read the answer?
Answer
DISJOINTNESS: stream Alice's set , then Bob's set . Then , so exactly when .
Solution
Items in exactly one set have frequency 1, items in both have frequency 2, contributing to . Alice sends the algorithm's memory and (in bits); Bob finishes the run and compares. A protocol for DISJOINTNESS needs bits even with randomization (Kalyanasundaram and Schnitger; Razborov), so the memory is (Space Lower Bounds). The same reduction fails for , which does not depend on the intersection, and that is why is easy.
Exercise 10: The right level
An -sampler subsamples the universe at rates . The final support has items. (a) At level , what is the expected number of surviving support items? (b) Modelling the number of survivors as Poisson, what is the probability that exactly one survives at levels 9, 10 and 11? (c) Why does the sampler succeed with constant probability overall?
Answer
(a) . (b) About , and . (c) Some level has in , where , and the detector returns an item whenever exactly one survives.
Solution
With , : at , gives ; at , ; at , . The sampler of Sparse Recovery and l0-Sampling scans the levels from the bottom and uses the first one that is exactly 1-sparse, so it fails only if no level is, an event of constant probability that independent repetitions drive down.
import math
s = 1000
for j in range(8, 13):
lam = s / 2 ** j
print(f"level {j:2}: expected survivors {lam:6.3f}, P[exactly one] = {lam * math.exp(-lam):.3f}")level 8: expected survivors 3.906, P[exactly one] = 0.079
level 9: expected survivors 1.953, P[exactly one] = 0.277
level 10: expected survivors 0.977, P[exactly one] = 0.368
level 11: expected survivors 0.488, P[exactly one] = 0.300
level 12: expected survivors 0.244, P[exactly one] = 0.191
Exercise 11: Cancelling edges
A graph on vertices has edges , and . Write the signed incidence vectors (coordinates indexed by edges, at the smaller endpoint, at the larger) and compute . Which edges does it contain, and why?
Answer
, , so : exactly the edges leaving .
Solution
The edge has both endpoints in and appears with in and in , so it cancels. The two edges with one endpoint in survive. By linearity of the sketch, adding the vertices' -sampler sketches samples one of these cut edges, which is the step Borůvka's algorithm needs (The AGM Sketch).
Exercise 12: When does uniform sampling sparsify?
Use the sampling rate for a graph with vertices and . (a) What is when the minimum cut is ? (b) And when ? (c) What does (a) tell you about sparsifying graphs with small minimum cuts?
Answer
(a) , so : no sparsification. (b) , keeping about 3% of the edges. (c) Uniform sampling needs a large minimum cut; for graphs with small cuts next to dense parts, importance sampling (Benczúr-Karger) is required.
Solution
. The rate comes from the Chernoff and cut-counting argument of Cut Sparsifiers: a cut of value must keep edges in expectation. If is small, every edge of a small cut must be kept with high probability, which uniform sampling can only do by keeping everything. Sampling by strength or connectivity keeps the weak edges and thins out the dense parts.
Exercise 13: Testing a huge sorted file
A file holds records that should be sorted. The binary-search tester runs searches. (a) How many record reads does it make for ? (b) If the file is -far from sorted, with what probability does the tester reject? (c) A corrupted file has exactly one pair of records swapped. Will the tester find it?
Answer
(a) searches of at most reads, about reads. (b) At least . (c) Probably not: the file is only -far from sorted, so it is close, and a tester may accept it.
Solution
(b) Each search starts at a bad index with probability at least (Testing Sortedness), so all 200 searches miss with probability at most . (c) A search reveals the swap only if it targets one of the two records or probes one of them on its path; that has probability far below 1. Testers make no promise for close inputs; detecting a single swapped pair requires reading records.
Exercise 14: How many BLR checks?
A function is -far from linear. (a) Lower-bound the probability that one BLR check rejects. (b) How many checks guarantee rejection with probability at least ? (c) How many queries is that, and how does it depend on the number of variables?
Answer
(a) At least . (b) , so 44 checks. (c) 132 queries, independent of the 40 variables.
Solution
By the Fourier analysis of Linearity Testing, . Independent checks all pass with probability at most , which is at most for . Each check reads three values.
Exercise 15: Space-Saving's smallest counter
Space-Saving with counters has read items. (a) Bound its smallest counter. (b) An item is reported with count and error bound . What do you know about its true frequency? (c) Is it certainly among the items with ?
Answer
(a) At most . (b) . (c) Yes: .
Solution
The 50 counters sum to , so the smallest is at most the average, (Space-Saving). The stored error is the count the item inherited when it last entered, so . The certified lower bound exceeds , so the item is a genuine heavy hitter without a second pass.
Test yourself
A count-min sketch must give error at most for all items simultaneously with probability . What changes compared with a single query?
- grows to
- Only the number of rows: by a union bound
- Nothing
- The hash functions must be -wise independent
Why does the reduction from DISJOINTNESS fail to show a lower bound for ?
- Because is approximate
- Because does not depend on the intersection
- Because DISJOINTNESS is easy
- Because needs two passes
With HyperLogLog at registers, roughly what relative standard error do you get?
- About 8%
- About 0.81%
- About 0.01%
- It depends on