COMPX270 — Randomised and Advanced Algorithms
Chapter 9: Streaming and Sketching II
Linear sketching, CountSketch with \(\ell_2\) guarantees, CountMinSketch with \(\ell_1\) guarantees, the turnstile streaming model, and comparisons of frequency estimation algorithms.
Strongly universal hash families, \(\ell_p\) norms, pairwise independence, Chebyshev’s inequality
Linear Sketching
What is a Sketch?
A sketching algorithm computes a compact summary (sketch) of a data stream that supports composability: given two streams, the sketch of their concatenation can be obtained from their individual sketches.
Definition: Linear Sketch
A streaming algorithm \(A\) is a linear sketch if for any two streams \(\sigma_1\) and \(\sigma_2\):
\[A(\sigma_1 \circ \sigma_2) = A(\sigma_1) + A(\sigma_2)\]Here \(\circ\) denotes stream concatenation and \(+\) denotes pointwise addition of the internal state. Linearity enables parallel and distributed processing of stream segments.
Why Linearity Matters
Parallelism
Split the stream across machines, sketch each part independently, then combine.
Mergeability
Two data centres can merge their sketches without re-processing the raw data.
Turnstile Support
Linearity naturally handles negative updates: subtract contributions.
Space Efficiency
The sketch is typically much smaller than the full frequency vector.
The Turnstile Model
Definition
In the turnstile model, each stream element is a pair \((j, c)\) where \(j \in [n]\) and \(c \in \{-B, \ldots, B\}\). The update means \(f_j \leftarrow f_j + c\). This generalises the cash register model (where \(c = 1\) always) by allowing negative updates.
Strict Turnstile Model
In the strict turnstile model, we additionally require \(f_j \geq 0\) at all times. This models real-world scenarios like inventory tracking where counts cannot go negative.
Cash Register
\(c = 1\) always. \(f_j \geq 0\).
Strict Turnstile
\(c \in \{-B, \ldots, B\}\). \(f_j \geq 0\) always.
General Turnstile
\(c \in \{-B, \ldots, B\}\). \(f_j\) may be negative.
CountSketch
Algorithm 19: CountSketch
Input: Stream \(\sigma\), parameters \(k, T\)
Hash functions: \(h_t : [n] \to [k]\) (strongly universal), \(g_t : [n] \to \{-1, +1\}\) (strongly universal), for \(t = 1, \ldots, T\)
Data structure: Array \(C[1..T][1..k]\), initialised to 0
- For each element \((j, c)\) in the stream:
- For each \(t = 1, \ldots, T\):
- \(C[t][h_t(j)] \leftarrow C[t][h_t(j)] + g_t(j) \cdot c\)
- On query for element \(j\):
- Return \(\hat{f}_j = \text{median}_{t=1}^{T}\{g_t(j) \cdot C[t][h_t(j)]\}\)
Theorem 44 (CountSketch Guarantee)
For any element \(j\), with \(k = \lceil 3/\varepsilon^2 \rceil\) and \(T = O(\log(1/\delta))\):
\[|\hat{f}_j - f_j| \leq \varepsilon \|f_{-j}\|_2\]with probability \(\geq 1 - \delta\), where \(\|f_{-j}\|_2 = \sqrt{\sum_{i \neq j} f_i^2}\) is the \(\ell_2\) norm of the frequency vector with element \(j\) removed.
Fix a row \(t\). Define \(X_t = g_t(j) \cdot C[t][h_t(j)]\). Then:
\[X_t = g_t(j) \sum_{i : h_t(i) = h_t(j)} g_t(i) \cdot f_i = f_j + \sum_{i \neq j : h_t(i) = h_t(j)} g_t(j) g_t(i) \cdot f_i\]Let \(Z_t = X_t - f_j = \sum_{i \neq j, h_t(i)=h_t(j)} g_t(j) g_t(i) f_i\). Using strong universality:
- \(\mathbb{E}[Z_t] = 0\) (since \(\mathbb{E}[g_t(j)g_t(i)] = 0\) for \(i \neq j\))
- \(\mathbb{E}[Z_t^2] \leq \|f_{-j}\|_2^2 / k\) (by pairwise independence of \(h_t\))
By Chebyshev with \(k = 3/\varepsilon^2\): \(\Pr[|Z_t| > \varepsilon\|f_{-j}\|_2] \leq 1/3\).
Taking the median over \(T = O(\log(1/\delta))\) rows, by Chernoff: \(\Pr[|\hat{f}_j - f_j| > \varepsilon\|f_{-j}\|_2] \leq \delta\). \(\square\)
Role of the Sign Function \(g\)
The function \(g_t : [n] \to \{-1, +1\}\) ensures that collisions cancel out in expectation. Without \(g\), collisions would always add positively, leading to systematic overestimation (like in CountMinSketch). The sign hash creates an unbiased estimator: \(\mathbb{E}[\hat{f}_j] = f_j\).
Probability Amplification: Median Trick
A single row gives correct estimates with probability \(\geq 2/3\). Running \(T = O(\log(1/\delta))\) independent rows and taking the median boosts success probability to \(1 - \delta\). This is the same median trick used in Chapter 8.
CountMinSketch
Algorithm 20: CountMinSketch
Input: Stream \(\sigma\) (cash register model), parameters \(k, T\)
Hash functions: \(h_t : [n] \to [k]\) (pairwise independent), for \(t = 1, \ldots, T\)
Data structure: Array \(C[1..T][1..k]\), initialised to 0
- For each element \(j\) in the stream (with implicit \(c = 1\)):
- For each \(t = 1, \ldots, T\):
- \(C[t][h_t(j)] \leftarrow C[t][h_t(j)] + 1\)
- On query for element \(j\):
- Return \(\hat{f}_j = \min_{t=1}^{T} C[t][h_t(j)]\)
Theorem 45 (CountMinSketch Guarantee)
With \(k = \lceil e/\varepsilon \rceil\) and \(T = \lceil \ln(1/\delta) \rceil\):
\[f_j \leq \hat{f}_j \leq f_j + \varepsilon \|f_{-j}\|_1\]with probability \(\geq 1 - \delta\), where \(\|f_{-j}\|_1 = \sum_{i \neq j} f_i = m - f_j\).
Lower bound: \(\hat{f}_j \geq f_j\) always, since every occurrence of \(j\) is counted in every row, and other elements only add to the count.
Upper bound: Fix row \(t\). Define \(Y_{t,j} = C[t][h_t(j)] - f_j = \sum_{i \neq j : h_t(i) = h_t(j)} f_i\). By Markov:
\[\mathbb{E}[Y_{t,j}] = \sum_{i \neq j} f_i \cdot \Pr[h_t(i) = h_t(j)] \leq \frac{\|f_{-j}\|_1}{k}\] \[\Pr[Y_{t,j} > \varepsilon \|f_{-j}\|_1] \leq \frac{1}{k\varepsilon} \leq \frac{1}{e}\]Since we take the minimum over \(T\) independent rows, the estimate exceeds \(f_j + \varepsilon\|f_{-j}\|_1\) only if all \(T\) rows exceed it:
\[\Pr[\hat{f}_j > f_j + \varepsilon\|f_{-j}\|_1] \leq \left(\frac{1}{e}\right)^T = e^{-T} \leq \delta\]Setting \(T = \lceil\ln(1/\delta)\rceil\) gives the result. \(\square\)
Built-in Probability Amplification
Unlike CountSketch, CountMinSketch does not need the median trick. The \(\min\) operation provides built-in probability amplification: each independent row is an independent chance for the estimate to be close to \(f_j\), and taking the minimum ensures we use the best one. The failure probability decays exponentially with \(T\).
One-Sided Error: Always Overestimates
CountMinSketch always satisfies \(\hat{f}_j \geq f_j\). This is because collisions only add to the count, never subtract. This is useful in applications where overestimation is acceptable but underestimation is dangerous (e.g., heavy hitter detection).
Comparison: MG vs CountSketch vs CountMinSketch
| Property | Misra-Gries | CountSketch | CountMinSketch |
|---|---|---|---|
| Type | Deterministic | Randomised | Randomised |
| Error bound | \(\varepsilon m\) (\(\ell_1\)) | \(\varepsilon \|f_{-j}\|_2\) (\(\ell_2\)) | \(\varepsilon \|f_{-j}\|_1\) (\(\ell_1\)) |
| Direction | Underestimates | Either direction | Overestimates |
| Space | \(O(k(\log m + \log n))\) | \(O\!\left(\frac{\log(nm)}{\varepsilon^2} \cdot \log\frac{1}{\delta}\right)\) | \(O\!\left(\frac{\log(nm)}{\varepsilon} \cdot \log\frac{1}{\delta}\right)\) |
| Stream model | Cash register | General turnstile | Cash register |
| Linear sketch? | No (weaker sketching) | Yes | Yes |
| Prob. amplification | N/A | Median trick | Built-in (min) |
\(\ell_1\) vs \(\ell_2\) Guarantees
The \(\ell_2\) guarantee of CountSketch is stronger when the frequency distribution is spread out (many elements with similar frequencies), since \(\|f_{-j}\|_2 \leq \|f_{-j}\|_1\). The \(\ell_1\) guarantee of CountMinSketch is better when there are a few dominant heavy hitters, and CountMinSketch uses less space (\(1/\varepsilon\) vs \(1/\varepsilon^2\) per row).
Interactive: CountSketch vs CountMinSketch Side-by-Side
Compare how CountSketch and CountMinSketch process the same stream with shared column hashes. CS uses sign hashes \(g(j)\in\{-1,+1\}\) for unbiased estimation; CMS always adds +1 and overestimates.
CountSketch
CountMinSketch
Interactive: CountMinSketch Simulator
Insert elements into a CountMinSketch with \(T = 3\) rows and \(k = 7\) columns. Observe how collisions affect the estimated frequencies.
Tutorial Problems
Work through these problems to solidify your understanding of sketching algorithms.
Problem 1 Warm-up
Describe the parallels between Bloom filters and CountMinSketch. How is the AND of bits in a Bloom filter analogous to the MIN of counts in CMS?
CountMinSketch is essentially a counting Bloom filter. In a Bloom filter, each element sets \(T\) bits (one per hash function) to 1. A query returns the AND of the \(T\) bits — all must be 1 for a positive. In CMS, each element increments \(T\) counters (one per hash function). A query returns the MIN of the \(T\) counters.
The parallel: BF has false positives (bits set by other elements), CMS has overestimation (counts inflated by collisions). BF uses AND to minimise false positives; CMS uses MIN to minimise overestimation. Both use \(T\) independent hash functions for probability amplification, and both have one-sided error.
Problem 2 Warm-up
Prove the monotonicity of \(\ell_p\) norms: for any vector \(x \in \mathbb{R}^d\),
\[\|x\|_\infty \leq \|x\|_2 \leq \|x\|_1\]Also show that \(\|x\|_2 \geq \|x\|_1 / \sqrt{d}\).
\(\|x\|_\infty \leq \|x\|_2\): Let \(x_k\) be the largest absolute value. Then \(\|x\|_\infty^2 = x_k^2 \leq \sum_i x_i^2 = \|x\|_2^2\).
\(\|x\|_2 \leq \|x\|_1\): \(\|x\|_2^2 = \sum x_i^2 \leq \left(\sum |x_i|\right)^2 = \|x\|_1^2\) since all cross-terms \(|x_i||x_j| \geq 0\).
\(\|x\|_2 \geq \|x\|_1/\sqrt{d}\): By Cauchy-Schwarz, \(\|x\|_1 = \sum |x_i| \cdot 1 \leq \sqrt{\sum x_i^2} \cdot \sqrt{d} = \|x\|_2 \sqrt{d}\). Rearranging gives the result. \(\square\)
Problem 3 Problem Solving ⭐
Compare Misra-Gries and CountMinSketch. What are the advantages and disadvantages of each? When would you prefer one over the other?
Misra-Gries advantages:
- Deterministic — guaranteed error bound with no probability of failure.
- Never overestimates: \(\hat{f}_j \leq f_j\).
- No hash functions needed.
CountMinSketch advantages:
- Linear sketch — composable, works in distributed settings.
- Easy point queries: \(O(T)\) time per query vs.\ \(O(\log k)\) for MG.
- Probability amplification is built-in.
- Simpler to implement for large \(k\).
Misra-Gries disadvantages: Not a linear sketch; hard to compose results from distributed computations. CMS disadvantage: always overestimates; requires randomness. \(\square\)
Problem 4 Problem Solving ⭐
Suppose you allocate the same total space budget to CountSketch and CountMinSketch. Compare the error guarantees. In what regime is each algorithm better?
For the same total space \(S\), ignoring logarithmic factors:
- CountSketch: Uses \(k = S\) columns per row. Error \(\leq \|f_{-j}\|_2 / \sqrt{k} = \|f_{-j}\|_2 / \sqrt{S}\).
- CountMinSketch: Uses \(k = S\) columns per row. Error \(\leq \|f_{-j}\|_1 / k = \|f_{-j}\|_1 / S\).
CS is better when \(\|f_{-j}\|_2 / \sqrt{S} < \|f_{-j}\|_1 / S\), i.e., when \(\|f_{-j}\|_1 / \|f_{-j}\|_2 > \sqrt{S}\). This happens when the frequency distribution is spread out (many elements with similar frequencies).
CMS is better when the frequency distribution is concentrated (a few heavy hitters dominate), so \(\|f_{-j}\|_1\) is relatively small compared to \(\|f_{-j}\|_2 \sqrt{S}\). \(\square\)
Problem 5 Problem Solving ⭐
Generalise CountMinSketch to work in the strict turnstile model (where \(f_j \geq 0\) always). What modifications are needed, and does the same guarantee hold?
In the strict turnstile model, updates are \((j, c)\) with \(c \in \{-B, \ldots, B\}\), but \(f_j \geq 0\) always. Modify CMS:
- Update: For each \(t\), set \(C[t][h_t(j)] \leftarrow C[t][h_t(j)] + c\) (allow negative increments).
- Query: Still return \(\hat{f}_j = \min_t C[t][h_t(j)]\).
The guarantee \(f_j \leq \hat{f}_j\) still holds because: at any time, \(C[t][h_t(j)] = f_j + \sum_{i \neq j, h_t(i) = h_t(j)} f_i \geq f_j\) since all \(f_i \geq 0\) in the strict turnstile model. The upper bound analysis also carries through since \(\|f_{-j}\|_1 = \sum_{i \neq j} f_i\) is still well-defined and non-negative. \(\square\)
Problem 6 Advanced ⭐⭐
Show that Misra-Gries is a sketching algorithm (in a non-linear sense). Given two MG outputs from independent runs on \(\sigma_1\) and \(\sigma_2\), describe how to combine them into a valid MG output for \(\sigma_1 \circ \sigma_2\). Is MG a linear sketch?
Combining MG outputs: Let \(\hat{f}^{(1)}\) and \(\hat{f}^{(2)}\) be the two MG outputs (associative arrays with at most \(k\) keys each).
- Add them pointwise: \(\hat{f}^{(\text{combined})}[j] = \hat{f}^{(1)}[j] + \hat{f}^{(2)}[j]\).
- If the combined output has more than \(k\) non-zero keys, find the \((k+1)\)-th largest value \(v_{k+1}\).
- Subtract \(v_{k+1}\) from all values and remove non-positive entries.
This preserves the MG invariant: at most \(k\) keys, and \(f_j - m/(k+1) \leq \hat{f}_j \leq f_j\). The combined error at most doubles: \(f_j - (m_1 + m_2)/(k+1) \leq \hat{f}_j \leq f_j\).
MG is NOT a linear sketch because the combination involves a non-linear step (finding the \((k+1)\)-th largest and subtracting). Linear sketches require only pointwise addition. \(\square\)
Problem 7 Advanced ⭐⭐
Modify CountMinSketch to output all \(\ell_1\) heavy hitters in the strict turnstile model: find all \(j\) with \(f_j \geq \varepsilon \|f\|_1\). What space does this require?
Approach: Run CMS with \(k = \lceil 2e/\varepsilon \rceil\) and \(T = \lceil \ln(n/\delta) \rceil\). Additionally, maintain \(\|f\|_1 = \sum_j f_j\) as a running counter (costs \(O(\log m)\) space).
Finding heavy hitters: After processing the stream, iterate over all \(j \in [n]\) and query CMS for each. Report \(j\) if \(\hat{f}_j \geq \varepsilon \|f\|_1\). By the CMS guarantee:
- If \(f_j \geq \varepsilon \|f\|_1\), then \(\hat{f}_j \geq f_j \geq \varepsilon \|f\|_1\), so \(j\) is reported (no false negatives).
- If \(f_j < \varepsilon \|f\|_1 / 2\), then with high probability \(\hat{f}_j < f_j + \varepsilon\|f\|_1/2 < \varepsilon\|f\|_1\), so \(j\) is not reported.
Space: \(O\!\left(\frac{\log(nm)}{\varepsilon} \cdot \log\frac{n}{\delta}\right)\). The query time is \(O(nT)\), which can be improved using a hierarchical scheme. \(\square\)
Chapter quizzes
Self-test and math questions for this chapter are in the Quiz Hub (practice or exam mode).