TExcelTAD

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 ℓ1\ell_1 or ℓ2\ell_2? 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 F2F_2 is hard communication lower bounds
10 The right level ℓ0\ell_0-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 k=3k = 3 items from a stream of m=20m = 20. (a) Item 5 enters the reservoir with probability 3/53/5 when it arrives. With what probability does it survive each later step t=6,…,20t = 6, \ldots, 20? (b) Multiply to get the probability that item 5 is in the final reservoir, and compare with the theorem.

Answer

(a) 1−1t1 - \frac{1}{t} at step tt. (b) 35∏t=620t−1t=35⋅520=320=km\frac{3}{5} \prod_{t=6}^{20} \frac{t-1}{t} = \frac{3}{5} \cdot \frac{5}{20} = \frac{3}{20} = \frac{k}{m}.

Solution

At step tt the new item is accepted with probability kt\frac{k}{t} and then replaces a uniformly chosen slot, so a particular member is evicted with probability kt⋅1k=1t\frac{k}{t} \cdot \frac{1}{k} = \frac{1}{t}. The product telescopes: ∏t=620t−1t=520\prod_{t=6}^{20}\frac{t-1}{t} = \frac{5}{20}. The result km\frac{k}{m} agrees with the theorem of Reservoir Sampling. The program checks the product exactly and by simulation.

python · try it yourself
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 k−1=99k - 1 = 99 counters reads m=106m = 10^6 items. At the end the counters sum to m′=400 000m' = 400\,000. (a) How many decrement steps happened? (b) What is the largest possible undercount of any item? (c) Compare with the generic bound m/km/k.

Answer

(a) (m−m′)/k=6000(m - m')/k = 6000. (b) 6000. (c) m/k=10 000m/k = 10\,000; the tighter bound is 40% smaller.

Solution

Each decrement step removes exactly k=100k = 100 units of count (99 counters and the arriving item), and every other step adds one, so m′=m−100dm' = m - 100d and d=6000d = 6000. 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 0.001⋅m0.001 \cdot m with probability 0.9990.999 per query, for a stream of m=109m = 10^9 items. (a) Give ww and dd. (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 10610^6 items of the universe at once?

Answer

(a) w=⌈e/0.001⌉=2719w = \lceil e/0.001 \rceil = 2719, d=⌈ln⁡1000⌉=7d = \lceil \ln 1000 \rceil = 7. (b) 19 03319\,033 counters, about 76 KB. (c) d=⌈ln⁡(109)⌉=21d = \lceil \ln(10^9) \rceil = 21, about 228 KB.

Solution

From the theorem of Count-Min in Depth: w=⌈e/ε⌉w = \lceil e/\varepsilon \rceil and d=⌈ln⁡(1/δ)⌉d = \lceil \ln(1/\delta) \rceil. For all items at once, use a union bound with δ′=δ/n=10−9\delta' = \delta/n = 10^{-9}, which only changes dd to ⌈ln⁡109⌉=21\lceil \ln 10^9 \rceil = 21. Counters of 4 bytes suffice because m<232m < 2^{32}. The memory does not depend on mm or nn beyond the logarithm in dd.

Exercise 4: ℓ1\ell_1 or ℓ2\ell_2?

A frequency vector over n=106n = 10^6 items has one item with frequency 10001000 and all others with frequency 1. Compute ∥f∥1\lVert f \rVert_1 and ∥f∥2\lVert f \rVert_2. With ε=0.01\varepsilon = 0.01, compare the error guarantees ε∥f∥1\varepsilon \lVert f \rVert_1 of count-min and ε∥f∥2\varepsilon \lVert f \rVert_2 of Count-Sketch, and the number of columns each needs.

Answer

∥f∥1=1 000 999\lVert f \rVert_1 = 1\,000\,999, ∥f∥2=106+999 999≈1414\lVert f \rVert_2 = \sqrt{10^6 + 999\,999} \approx 1414. Count-min: error about 10 01010\,010 with ⌈e/0.01⌉=272\lceil e/0.01 \rceil = 272 columns. Count-Sketch: error about 1414 with O(1/ε2)=O(104)O(1/\varepsilon^2) = O(10^4) columns.

Solution

∥f∥22=10002+(106−1)⋅1=1 999 999\lVert f \rVert_2^2 = 1000^2 + (10^6 - 1) \cdot 1 = 1\,999\,999. 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 1/ε21/\varepsilon^2 columns (Count-Sketch). For this flat-tailed vector, the ℓ2\ell_2 guarantee is worth the extra space.

Exercise 5: Tug of war by hand

Let f=(3,−1,2)f = (3, -1, 2) and Z=∑isifiZ = \sum_i s_i f_i with independent uniform signs si∈{±1}s_i \in \{\pm 1\}. Compute E[Z2]\mathbb{E}[Z^2] and Var⁡[Z2]\operatorname{Var}[Z^2] directly from the 8 sign vectors, and compare with F2F_2 and 2(F22−F4)2(F_2^2 - F_4).

Answer

E[Z2]=14=F2\mathbb{E}[Z^2] = 14 = F_2 and Var⁡[Z2]=196=2(142−98)\operatorname{Var}[Z^2] = 196 = 2(14^2 - 98).

Solution

F2=9+1+4=14F_2 = 9 + 1 + 4 = 14 and F4=81+1+16=98F_4 = 81 + 1 + 16 = 98, so the formula of the AMS sketch gives 2(196−98)=1962(196 - 98) = 196. The program enumerates the sign vectors (fully independent signs are in particular 4-wise independent).

python · try it yourself
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 m=109m = 10^9 events. (a) About what value does XX reach, and how many bits does it need? (b) What is the standard deviation of one estimate 2X−12^X - 1? (c) How many independent copies must be averaged so that Chebyshev guarantees error at most 10%10\% with probability 23\frac{2}{3}?

Answer

(a) About log⁡2109≈30\log_2 10^9 \approx 30, so 5 bits. (b) m(m−1)/2≈0.71⋅109\sqrt{m(m-1)/2} \approx 0.71 \cdot 10^9. (c) k≥32⋅0.01=150k \ge \frac{3}{2 \cdot 0.01} = 150.

Solution

(a) E[2X]=m+1\mathbb{E}[2^X] = m + 1, so XX is close to log⁡2m≈29.9\log_2 m \approx 29.9, and values up to 31 fit in 5 bits. (b) Var⁡[2X−1]=m(m−1)2\operatorname{Var}[2^X - 1] = \frac{m(m-1)}{2} (Space as the Resource). (c) The average of kk copies has variance below m22k\frac{m^2}{2k}, and Chebyshev gives failure probability below 12kε2\frac{1}{2k\varepsilon^2}; requiring this to be at most 13\frac{1}{3} with ε=0.1\varepsilon = 0.1 gives k≥150k \ge 150: 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 10610^6 or 101210^{12} distinct items?

Answer

(a) m≥(1.04/0.01)2=10 816m \ge (1.04/0.01)^2 = 10\,816, so m=214=16 384m = 2^{14} = 16\,384 registers, 12 KiB. (b) 1.04/128≈0.81%1.04/128 \approx 0.81\%. (c) A register stores a rank of about log⁡2(n/m)\log_2(n/m), which fits in 6 bits for any nn up to 2642^{64}.

Solution

The standard error is βm/m\beta_m/\sqrt{m} with β∞≈1.04\beta_\infty \approx 1.04 (HyperLogLog). Solving for mm gives about 10 81610\,816, and the next power of two is 2142^{14}, with 214=128\sqrt{2^{14}} = 128. The memory is 16 384×616\,384 \times 6 bits =98 304= 98\,304 bits =12= 12 KiB, the same as Redis's implementation. Only the register width grows with nn, and only like log⁡log⁡n\log\log n.

Exercise 8: Reading a KMV sketch

A KMV sketch with k=1024k = 1024 has, as its largest stored hash value normalized to [0,1)[0, 1), vk=0.000512v_k = 0.000512. (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) 10230.000512≈1.998⋅106\frac{1023}{0.000512} \approx 1.998 \cdot 10^6. (b) About 11022≈3.1%\frac{1}{\sqrt{1022}} \approx 3.1\%. (c) The Jaccard similarity of the two sets, about 3001024≈0.29\frac{300}{1024} \approx 0.29.

Solution

The unbiased KMV estimator is (k−1)/vk(k - 1)/v_k, with relative standard deviation at most 1/k−21/\sqrt{k - 2} (Flajolet-Martin and k Minimum Values). In (c), the kk smallest values of the union are a uniform sample of the union's distinct items, and the fraction present in both sketches estimates ∣A∩B∣/∣A∪B∣\lvert A \cap B \rvert / \lvert A \cup B \rvert.

Exercise 9: Exact F2F_2 is hard

Show that every randomized one-pass algorithm that computes F2F_2 exactly with probability 23\frac{2}{3} needs Ω(n)\Omega(n) bits. Which communication problem do you reduce from, and how does Bob read the answer?

Answer

DISJOINTNESS: stream Alice's set AA, then Bob's set BB. Then F2=∣A∣+∣B∣+2∣A∩B∣F_2 = \lvert A \rvert + \lvert B \rvert + 2\lvert A \cap B \rvert, so A∩B=∅A \cap B = \emptyset exactly when F2=∣A∣+∣B∣F_2 = \lvert A \rvert + \lvert B \rvert.

Solution

Items in exactly one set have frequency 1, items in both have frequency 2, contributing 4=1+1+24 = 1 + 1 + 2 to F2F_2. Alice sends the algorithm's memory and ∣A∣\lvert A \rvert (in O(log⁡n)O(\log n) bits); Bob finishes the run and compares. A protocol for DISJOINTNESS needs Ω(n)\Omega(n) bits even with randomization (Kalyanasundaram and Schnitger; Razborov), so the memory is Ω(n)\Omega(n) (Space Lower Bounds). The same reduction fails for F1=∣A∣+∣B∣F_1 = \lvert A \rvert + \lvert B \rvert, which does not depend on the intersection, and that is why F1F_1 is easy.

Exercise 10: The right level

An ℓ0\ell_0-sampler subsamples the universe at rates 2−j2^{-j}. The final support has s=1000s = 1000 items. (a) At level j=10j = 10, 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) 1000/1024≈0.981000/1024 \approx 0.98. (b) About 0.280.28, 0.370.37 and 0.300.30. (c) Some level has λ=s/2j\lambda = s/2^j in [12,1)[\frac{1}{2}, 1), where λe−λ≥0.30\lambda e^{-\lambda} \ge 0.30, and the detector returns an item whenever exactly one survives.

Solution

With λj=s/2j\lambda_j = s/2^j, Pr⁡[exactly one]≈λje−λj\Pr[\text{exactly one}] \approx \lambda_j e^{-\lambda_j}: at j=9j = 9, λ=1.95\lambda = 1.95 gives 0.2770.277; at j=10j = 10, 0.977⋅e−0.977≈0.3680.977 \cdot e^{-0.977} \approx 0.368; at j=11j = 11, 0.488⋅e−0.488≈0.3000.488 \cdot e^{-0.488} \approx 0.300. 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.

python · try it yourself
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 {1,2,3,4}\{1, 2, 3, 4\} has edges {1,2}\{1, 2\}, {2,3}\{2, 3\} and {1,4}\{1, 4\}. Write the signed incidence vectors a1,a2a_1, a_2 (coordinates indexed by edges, +1+1 at the smaller endpoint, −1-1 at the larger) and compute a1+a2a_1 + a_2. Which edges does it contain, and why?

Answer

a1=(+1{1,2},+1{1,4})a_1 = (+1_{\{1,2\}}, +1_{\{1,4\}}), a2=(−1{1,2},+1{2,3})a_2 = (-1_{\{1,2\}}, +1_{\{2,3\}}), so a1+a2=(+1{2,3},+1{1,4})a_1 + a_2 = (+1_{\{2,3\}}, +1_{\{1,4\}}): exactly the edges leaving {1,2}\{1, 2\}.

Solution

The edge {1,2}\{1, 2\} has both endpoints in S={1,2}S = \{1, 2\} and appears with +1+1 in a1a_1 and −1-1 in a2a_2, so it cancels. The two edges with one endpoint in SS survive. By linearity of the sketch, adding the vertices' ℓ0\ell_0-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 p=min⁡(1,3ln⁡nε2c)p = \min\bigl(1, \frac{3\ln n}{\varepsilon^2 c}\bigr) for a graph with n=104n = 10^4 vertices and ε=0.1\varepsilon = 0.1. (a) What is pp when the minimum cut is c=1000c = 1000? (b) And when c=105c = 10^5? (c) What does (a) tell you about sparsifying graphs with small minimum cuts?

Answer

(a) 3⋅9.210.01⋅1000≈2.76\frac{3 \cdot 9.21}{0.01 \cdot 1000} \approx 2.76, so p=1p = 1: no sparsification. (b) p≈0.028p \approx 0.028, 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

ln⁡104≈9.21\ln 10^4 \approx 9.21. The rate comes from the Chernoff and cut-counting argument of Cut Sparsifiers: a cut of value αc\alpha c must keep Ω(αlog⁡n/ε2)\Omega(\alpha \log n/\varepsilon^2) edges in expectation. If cc 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 n=230n = 2^{30} records that should be sorted. The binary-search tester runs ⌈2/ε⌉\lceil 2/\varepsilon \rceil searches. (a) How many record reads does it make for ε=0.01\varepsilon = 0.01? (b) If the file is 0.010.01-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) 200200 searches of at most 3131 reads, about 62006200 reads. (b) At least 1−0.99200≈0.8661 - 0.99^{200} \approx 0.866. (c) Probably not: the file is only 2/n2/n-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 ε\varepsilon (Testing Sortedness), so all 200 searches miss with probability at most 0.99200≈0.1340.99^{200} \approx 0.134. (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 Ω(n)\Omega(n) records.

Exercise 14: How many BLR checks?

A function f:F240→F2f : \mathbb{F}_2^{40} \to \mathbb{F}_2 is 0.10.1-far from linear. (a) Lower-bound the probability that one BLR check rejects. (b) How many checks guarantee rejection with probability at least 0.990.99? (c) How many queries is that, and how does it depend on the number of variables?

Answer

(a) At least 0.10.1. (b) t≥ln⁡(100)/(−ln⁡0.9)≈43.7t \ge \ln(100)/(-\ln 0.9) \approx 43.7, so 44 checks. (c) 132 queries, independent of the 40 variables.

Solution

By the Fourier analysis of Linearity Testing, ρ(f)≥dist⁡(f)≥0.1\rho(f) \ge \operatorname{dist}(f) \ge 0.1. Independent checks all pass with probability at most 0.9t0.9^t, which is at most 0.010.01 for t≥44t \ge 44. Each check reads three values.

Exercise 15: Space-Saving's smallest counter

Space-Saving with k=50k = 50 counters has read m=200 000m = 200\,000 items. (a) Bound its smallest counter. (b) An item is reported with count 90009000 and error bound 20002000. What do you know about its true frequency? (c) Is it certainly among the items with fx>m/kf_x > m/k?

Answer

(a) At most m/k=4000m/k = 4000. (b) 7000≤fx≤90007000 \le f_x \le 9000. (c) Yes: 7000>40007000 > 4000.

Solution

The 50 counters sum to mm, so the smallest is at most the average, 40004000 (Space-Saving). The stored error is the count the item inherited when it last entered, so C[x]−err[x]≤fx≤C[x]C[x] - \text{err}[x] \le f_x \le C[x]. The certified lower bound 70007000 exceeds m/km/k, so the item is a genuine heavy hitter without a second pass.

Test yourself

A count-min sketch must give error at most εm\varepsilon m for all nn items simultaneously with probability 1−δ1 - \delta. What changes compared with a single query?

  1. ww grows to en/εe n/\varepsilon
  2. Only the number of rows: d=⌈ln⁡(n/δ)⌉d = \lceil \ln(n/\delta) \rceil by a union bound
  3. Nothing
  4. The hash functions must be nn-wise independent

Why does the reduction from DISJOINTNESS fail to show a lower bound for F1F_1?

  1. Because F1F_1 is approximate
  2. Because F1=∣A∣+∣B∣F_1 = \lvert A \rvert + \lvert B \rvert does not depend on the intersection
  3. Because DISJOINTNESS is easy
  4. Because F1F_1 needs two passes

With HyperLogLog at m=214m = 2^{14} registers, roughly what relative standard error do you get?

  1. About 8%
  2. About 0.81%
  3. About 0.01%
  4. It depends on nn