Module contents
Lesson 24 of 33Advanced 110 min

Streaming algorithms and sketches

When data passes once and does not fit in memory, answer using sublinear summaries. Study the streaming model, reservoir sampling, Misra–Gries heavy hitters, Bloom filters, count-min and Count Sketch, HyperLogLog distinct counting and mergeability for distributed systems.

After this lesson you can

  • Formulate (ε, δ) streaming guarantees and reason about memory bounds.
  • Implement reservoir sampling and prove uniformity.
  • Size a Bloom filter and count-min sketch for a target error.
  • Implement HyperLogLog with corrections and measure relative error.
  • Merge sketches from data fragments and choose the right sketch for each query.

Before you start

Motivation: one pass and very little memory

Three problems that seem trivial until data size is considered:

  • Distinct IP addresses. A provider’s router sees tens of millions of packets per second and wants distinct source IPs per minute: a sudden jump indicates a distributed denial-of-service attack. Storing exact seen IPv6 addresses requires memory proportional to their number, in a router data plane with only a few megabytes of SRAM.
  • Most visited URLs. A service with billions of daily requests wants the most requested routes per hour and region. A dictionary of exact counts grows with distinct routes, including the long tail of URLs requested once.
  • Previously seen documents. A crawler that downloaded ten billion pages must decide for each new link whether it has visited it. A hash table of URLs averaging 80 bytes would need almost a terabyte of RAM.

In all three cases data arrives as a stream, can be read once and does not fit in memory. This lesson gives up exactness in a controlled way: maintain a sublinear sketch, often kilobytes, answering with bounded error and bounded failure probability. With 12 KiB, HyperLogLog counts billions of distinct elements with typical error 0.81%. With 1.2 MB, a Bloom filter answers “have I seen this URL?” for one million URLs with 1% false positives and no false negatives.

Everything builds on universal hashing and k-wise independence: a hash turns arbitrary elements, perhaps adversarially chosen, into values behaving randomly, and Markov, Chebyshev and Chernoff inequalities turn that behavior into guarantees.

The streaming model

Three variants depend on how f\vb{f} changes:

  • Insert-only (cash register): each ata_t adds 1 to fatf_{a_t}. This covers logs and network traffic.
  • Turnstile: each update is a pair (x,Δ)(x, \Delta) with Δ∈Z\Delta \in \Z possibly negative, and fx+=Δf_x \mathrel{+}= \Delta. If additionally fx≥0f_x \ge 0 always (nothing absent is deleted), it is strict turnstile. General turnstile can subtract yesterday’s window from today’s or compare two streams.
  • Sliding window: only the most recent WW elements count. We do not cover it here.

Typical queries are functions of f\vb{f}: number of distinct elements F0=∣{x:fx≠0}∣F_0 = \abs{\{x : f_x \ne 0\}}, length F1=∑xfx=nF_1 = \sum_x f_x = n, second moment F2=∑xfx2=∥f∥22F_2 = \sum_x f_x^2 = \norm{\vb{f}}_2^2 (measuring distribution concentration; Alon, Matias and Szegedy, 1999, studied moments FkF_k generally), a frequency fxf_x, elements with fx>ϕnf_x > \phi n or a uniform sample.

That last sentence distinguishes average-case analysis. URLs are not assumed to follow a friendly distribution: the adversary fixes the stream, then hash functions are drawn. This is the universal-hashing contract and has the same caveat: if the adversary sees the functions, the guarantee disappears.

Why something must be sacrificed

Must we approximate and randomize? For distinct count, yes, and the proof is a clean communication argument.

Proof

For each subset S⊆[U]S \subseteq [U], feed the algorithm elements of SS in increasing order and call the resulting memory state σ(S)\sigma(S). Show S≠TS \ne T implies σ(S)≠σ(T)\sigma(S) \ne \sigma(T). If ∣S∣≠∣T∣\abs{S} \ne \abs{T}, ending the stream there gives different answers ∣S∣\abs{S} and ∣T∣\abs{T}, so states differ because the answer depends only on state. If ∣S∣=∣T∣\abs{S} = \abs{T}, take x∈S∖Tx \in S \setminus T and append xx to both streams: correct answers are ∣S∣\abs{S} and ∣T∣+1=∣S∣+1\abs{T} + 1 = \abs{S} + 1 respectively. The algorithm is deterministic, so identical states and continuation would give the same answer; hence σ(S)≠σ(T)\sigma(S) \ne \sigma(T). There are 2U2^U subsets and therefore at least 2U2^U states requiring UU bits.

∎

This is a special case of a general technique: memory state is a message the first stream half sends to the second, so a one-way communication complexity lower bound gives a memory lower bound. INDEX (Alice has an UU-bit vector, Bob an index ii and must find bit ii from one Alice message) requires Ω(U)\Omega(U) bits even with randomness, implying exact distinct counting needs linear memory even if failure probability 1/31/3 is allowed. Conversely, Alon, Matias and Szegedy proved a deterministic algorithm cannot approximate F0F_0 with small relative error without linear memory either. Both concessions, approximation and randomness, are necessary. Even with both, approximating F0F_0 with relative error ε\eps requires Ω(1/ε2)\Omega(1/\eps^2) bits (Indyk and Woodruff, 2003, using Gap-Hamming), so HyperLogLog’s 1/m1/\sqrt{m} is essentially unimprovable.

QueryStructureMemoryGuaranteeMerge
uniform sample of kkreservoirkk elementsexact distributionrandom keys
elements with fx>n/(k+1)f_x > n/(k+1)Misra–Grieskk countersfx−n/(k+1)≤f^x≤fxf_x - n/(k+1) \le \hat f_x \le f_xyes
is xx present?Bloom filter1.44log⁡2(1/p)1.44 \log_2(1/p) bits per elementno false negatives, false positives ppbitwise OR
approximate fxf_xcount-min⌈e/ε⌉×⌈ln⁡(1/δ)⌉\lceil e/\eps\rceil \times \lceil\ln(1/\delta)\rceil countersf^x≤fx+εn\hat f_x \le f_x + \eps n with prob. 1−δ1 - \deltasum
unbiased fxf_xCount SketchO(ε−2log⁡(1/δ))\bigO(\eps^{-2}\log(1/\delta)) counters∣f^x−fx∣≤ε∥f∥2\abs{\hat f_x - f_x} \le \eps\norm{\vb{f}}_2 with prob. 1−δ1 - \deltasum
distinct countHyperLogLogmm 6-bit registerstypical error 1.04/m1.04/\sqrt{m}maximum

Reservoir sampling

The simplest problem: retain kk uniformly random elements from a stream of unknown length. If nn were known, drawing kk positions would suffice. Without it, maintain a valid sample of the prefix at every instant.

For k=1k = 1 the calculation is a telescoping product. Element aia_i enters with probability 1/i1/i and survives each later asa_s with probability 1−1/s=(s−1)/s1 - 1/s = (s - 1)/s:

P(R=ai al final)=1i⋅ii+1⋅i+1i+2⋯n−1n=1n.\Pr(R = a_i \text{ al final}) = \frac{1}{i}\cdot\frac{i}{i+1}\cdot\frac{i+1}{i+2}\cdots\frac{n-1}{n} = \frac{1}{n}.

Prove the general case in the guided exercise by induction on tt, separating whether the last element belongs to the subset. The theorem says more than “each element is present with probability k/tk/t”: the entire sample is uniform, so any statistic computed on it has the same distribution as on a sample without replacement drawn knowing nn. The first lab cell checks this with a chi-square test over all 15 possible subsets.

Three extensions used in practice:

  • Skipping (algorithm L). Drawing once per element is costly for a huge stream and small kk because almost everything is discarded. Li (1994) directly draws how many to skip, reducing expected draws to O(k(1+log⁡(n/k)))\bigO(k(1 + \log(n/k))).
  • Weighted sampling. If each element has weight wi>0w_i > 0, Efraimidis and Spirakis (2006) assign key ui1/wiu_i^{1/w_i} with ui∼Unif⁡(0,1)u_i \sim \Unif(0, 1) and keep the kk largest (a size-kk heap). With k=1k = 1, ii is selected with probability exactly wi/∑jwjw_i / \sum_j w_j; with k>1k > 1 the result is successive sampling without replacement proportional to weights.
  • Random keys (bottom-k). Assign each element a key ui∼Unif⁡(0,1)u_i \sim \Unif(0, 1) and retain the kk smallest; this gives exactly the reservoir distribution because all key orders are equiprobable. Two stream samples combine by retaining the kk smallest in their union. This returns in the merge section.

Frequent elements: Misra–Gries and Space-Saving

Finding exact heavy hitters requires linear memory (by the same type of argument as before). But every element exceeding a fixed stream fraction can be found. The idea, going back to Boyer–Moore majority, is to cancel occurrences of different elements: if one occupies over half the stream, it survives any pairing with different elements.

Proof

xx’s counter increases only when xx arrives, so f^x≤fx\hat f_x \le f_x. Difference fx−f^xf_x - \hat f_x increases by one only when xx arrives and is discarded in a decrement step, or xx has a counter that is decremented. Both happen in decrement steps, at most once per step, so fx−f^x≤Df_x - \hat f_x \le D. To bound DD, count units: every read element contributes one unit to counter sum, and each decrement step destroys k+1k + 1 (one from each of kk counters and the discarded element’s). Since final sum ∑xf^x\sum_x \hat f_x is nonnegative, n−(k+1)D≥0n - (k+1)D \ge 0, i.e. D≤n/(k+1)D \le n/(k+1). If fx>n/(k+1)≥Df_x > n/(k+1) \ge D, then f^x≥fx−D>0\hat f_x \ge f_x - D > 0.

∎

Amortized cost per element is O(1)\bigO(1): a decrement traverses kk counters, but each decremented unit was created by a previous increment, so total decrement work is at most nn. A bucket list by counter value (Demaine, López-Ortiz and Munro, 2002) gives worst-case O(1)\bigO(1).

Space-Saving (Metwally, Agrawal and El Abbadi, 2005) changes the full-table rule: the newcomer replaces the minimum-count element cmin⁡c_{\min} and inherits cmin⁡+1c_{\min} + 1. Counter sum is always nn, estimates become overestimates, fx≤f^x≤fx+cmin⁡f_x \le \hat f_x \le f_x + c_{\min}, and since k cmin⁡≤nk\,c_{\min} \le n, every element with fx>n/kf_x > n/k is in the table. The two algorithms are essentially the same: Agarwal and coauthors (2012) proved Space-Saving with k+1k + 1 counters and Misra–Gries with kk retain the same information; Space-Saving often estimates top ranks more accurately in practice.

Interactivek counters for frequent elements
The stream (current letter in magenta)
DACAAFACAEFBAADEACEDCDCBAAGBBDDAAFAIBAEA
“A” arrives with an existing counter: increment it.
The 3 counters
A
7
E
1
·
0
True frequency (gray) and estimate (blue) for each letter
A
15 / 7
B
5 / 0
C
5 / 0
D
6 / 0
E
4 / 1
F
3 / 0
G
1 / 0
H
0 / 0
I
1 / 0
J
0 / 0
  • true frequency
  • estimate
  • threshold n/(k+1)n/(k+1)
Summary
Algorithm
3
Stream
n = 40
Items processed nn40
Decrement steps DD8
Threshold n/(k+1)n/(k+1)10.00
Letters with f>n/(k+1)f > n/(k+1)A
Every letter with f>n/(k+1)f > n/(k+1) has a counter. Each estimate satisfies f−D≤f^≤ff - D \le \hat f \le f and D≤n/(k+1)D \le n/(k+1).
A stream of 40 letters with A very frequent. Step through: when an untracked letter arrives and no space remains, Misra–Gries subtracts 1 from all (red dashed border) and forgets the newcomer; each step destroys k+1k + 1 occurrences, so there can be at most n/(k+1)n/(k+1). On the right, true frequency (gray) versus estimate (blue) per letter and orange threshold: letters above it never lose their counters. Switch to Space-Saving and see the newcomer inherit the minimum count (red bar portion is inherited excess): it now overestimates rather than underestimates. Try k=1k = 1: this is Boyer–Moore majority.

Bloom filter

A Bloom filter answers membership with false positives but no false negatives, using a fraction of exact-set memory. It is the lesson’s oldest sketch: Burton Bloom proposed it in 1970 for a hyphenation dictionary that did not fit in memory.

If xx was inserted, its kk bits are 1 and the answer is “possibly present”: no false negatives. A false positive occurs when other keys have set all kk bits of an absent xx.

Proof

Each of the knkn written positions is uniform and independent, and a fixed bit avoids each with probability 1−1/m1 - 1/m; hence the first formula and (1−1/m)kn=eknln⁡(1−1/m)≈e−kn/m(1 - 1/m)^{kn} = e^{kn\ln(1 - 1/m)} \approx e^{-kn/m}. An absent key has kk new independent positions; approximating the fraction of 1 bits by its expectation 1−e−kn/m1 - e^{-kn/m}, all kk hit 1 bits with probability (1−e−kn/m)k(1 - e^{-kn/m})^k. To optimize, write q=e−kn/mq = e^{-kn/m}, so k=−mnln⁡qk = -\frac{m}{n}\ln q and

ln⁡p=kln⁡(1−q)=−mn ln⁡q ln⁡(1−q).\ln p = k\ln(1 - q) = -\frac{m}{n}\,\ln q\,\ln(1 - q).

Maximize φ(q)=ln⁡q ln⁡(1−q)\varphi(q) = \ln q\,\ln(1 - q) on (0,1)(0, 1), symmetric about q=1/2q = 1/2. With u(q)=qln⁡qu(q) = q\ln q, its derivative is φ′(q)=−g(q)/(q(1−q))\varphi'(q) = -g(q)/\big(q(1 - q)\big), where g(q)=u(q)−u(1−q)g(q) = u(q) - u(1 - q). This gg tends to 0 at 0+0^+, vanishes at 1/21/2 and derivative g′(q)=2+ln⁡(q(1−q))g'(q) = 2 + \ln\big(q(1 - q)\big) is negative near 0 and positive from q≈0.16q \approx 0.16 to 1/21/2; hence g<0g < 0 on (0,1/2)(0, 1/2), φ\varphi increases to 1/21/2 and by symmetry decreases afterward. Maximum of φ\varphi, hence minimum of pp, is at q=1/2q = 1/2. Then e−kn/m=1/2e^{-kn/m} = 1/2 gives k∗=mnln⁡2k^* = \frac{m}{n}\ln 2 and p∗=(1/2)k∗=e−mn(ln⁡2)2≈0.6185m/np^* = (1/2)^{k^*} = e^{-\frac{m}{n}(\ln 2)^2} \approx 0.6185^{m/n}.

∎

The second formula is approximate: bits are not independent (if one is 1 another is slightly likelier 0 because the sum is bounded). Bose and coauthors (2008) showed the exact rate is somewhat higher than (1−e−kn/m)k(1 - e^{-kn/m})^k, with negligible difference for mm of thousands of bits onward. The optimum has a nice interpretation: with k∗k^* hashes half the bits are 1, the array has maximum entropy and each of the kk bits checked by an absent key is 1 with probability 1/21/2, so each hash halves the rate.

InteractiveBloom filter false positives
The array: m=256m = 256 bits, n=32n = 32 keys, k=3k = 3 (82 bits set)
48 queries for absent keys: 1 false positive(s)
Query 30: all 3 positions are 1 (red outline), although the key was never inserted. False positive.
False-positive rate versus kk (log scale)
  • measured
  • theory (1 − e^(−kn/m))^k
  • k* = (m/n) ln 2
  • bit set to 1
  • query position at 0
  • query position at 1
Size
256
32
Hashes
3
How positions are chosen
Measured false positives (20,000 queries)3.2 %
Theory (1−e−kn/m)k(1 - e^{-kn/m})^k3.1 %
Bits set: measured / 1−e−kn/m1 - e^{-kn/m}0.320 / 0.313
Optimum k∗=(m/n)ln⁡2k^* = (m/n)\ln 25.55 (best measured integer: 5)
Minimum rate 2−k∗2^{-k^*} and bits per key2.1 % with 8.0 bits/key
Too few hashes: 68% of the array remains 0, but a query checks only 3 bit(s). Increase kk toward k∗=(m/n)ln⁡2≈5.5k^* = (m/n)\ln 2 \approx 5.5.
The mm-bit array after inserting nn keys with kk hashes. The 48 boxes below query never-inserted keys: false positives are red. Click one to see its kk positions: green outlines mark zeros (one suffices for ‘absent’) and red outlines ones. Right, measured rate over 20 000 queries versus the formula. Move kk and find the minimum: at magenta line k∗=(m/n)ln⁡2k^* = (m/n)\ln 2, almost exactly half the bits are 1. Then choose consecutive positions (a key’s kk positions from one hash): with the same mm, nn and kk the rate spikes because positions are no longer independent.

Size a filter

Solving p∗=e−mn(ln⁡2)2p^* = e^{-\frac{m}{n}(\ln 2)^2} for mm gives the design formula:

m=nln⁡(1/p)(ln⁡2)2≈1.44 nlog⁡2(1/p),k=mnln⁡2=log⁡2(1/p).m = \frac{n \ln(1/p)}{(\ln 2)^2} \approx 1.44\, n \log_2(1/p), \qquad k = \frac{m}{n}\ln 2 = \log_2(1/p).

A 1% false-positive rate costs 9.6 bits per key and 7 hashes; 0.1% costs 14.4 bits and 10 hashes. Key size does not appear: a filter for 80-byte URLs occupies the same as one for integers. No false-negative-free structure with rate pp can use fewer than nlog⁡2(1/p)n\log_2(1/p) bits in the worst case (Carter, Floyd, Gill, Markowsky and Wegman, 1978), so Bloom pays factor 1/ln⁡2≈1.441/\ln 2 \approx 1.44 over optimum.

Hash functions and variants

The analysis assumes kk independent functions. Computing kk genuine hashes costs time, tempting us to derive positions from one. This must be done correctly:

  • Double hashing. Kirsch and Mitzenmacher (2006) proved gi(x)=h1(x)+i h2(x) mod mg_i(x) = h_1(x) + i\,h_2(x) \bmod m, with independent h1,h2h_1, h_2, asymptotically retains the same false-positive rate. Two hashes suffice. Avoid h2(x)h_2(x) being 0 or sharing factors with mm, which makes the kk positions repeat.
  • Correlated positions. Using h(x),h(x)+1,…,h(x)+k−1h(x), h(x) + 1, \dots, h(x) + k - 1 or taking kk pieces of a hash that is too short breaks independence: two keys whose first bit is in one area share almost all the rest. In the lab, with 1% sizing, consecutive positions give 23% false positives.

Variants address limitations of the basic filter:

  • Deletion. A standard filter cannot delete: clearing xx bits also clears bits of other keys, creating false negatives. A counting filter (Fan, Cao, Almeida and Broder, 2000) replaces each bit with a 4-bit counter, incremented on insertion and decremented on deletion, quadrupling memory (with possible, though unlikely, overflow).
  • Cuckoo filter. Fan, Andersen, Kaminsky and Mitzenmacher (2014) store an ff-bit fingerprint per key in a cuckoo hash table with two candidate buckets, the second calculated as the first XOR fingerprint hash, permitting relocation without knowing the key. It supports deletion and for rates below about 3% uses less space than Bloom.
  • Blocked filters. To make each query touch one cache line, first choose a 512-bit block by hash and place the kk positions inside. False-positive rate worsens slightly but speed improves greatly.

Count-min and Count Sketch

Now estimate frequency fxf_x of any element, not just the most frequent, in the turnstile model.

Each row is a keyless hash table: xx’s cell accumulates fxf_x plus frequencies of all elements colliding with xx. In strict turnstile those frequencies are nonnegative, so each row overestimates and the minimum is the row with least noise.

The proof uses Markov’s inequality per row (universal hrh_r suffices to bound expected noise by ∥f∥1/w\norm{\vb{f}}_1/w) and independence between rows; you will do it in the exercise. Choice w=e/εw = e/\eps is not accidental: it minimizes total memory wdwd for given ε\eps and δ\delta. With ε=10−3\eps = 10^{-3} and δ=10−2\delta = 10^{-2}, 2719×5=13 5952719 \times 5 = 13\,595 counters are needed whether the universe has thousands or billions of elements.

The price is the word additive. Error is measured against ∥f∥1=n\norm{\vb{f}}_1 = n, the whole stream size, not fxf_x. For an element with fx=0.05 nf_x = 0.05\,n and ε=10−3\eps = 10^{-3} relative error is at most 2%. For one with fx=3f_x = 3 in a stream of 10610^6, the bound permits estimate 10031003.

InteractiveCount-min with a Zipf distribution
Estimated versus true frequency: U=1000U = 1000 items, N=50 000N = 50\,000 occurrences, 128 × 4 counters
110100100010 k110100100010 ktrue frequency f (log scale)estimate (log scale)
  • top 10 items
  • inside the bound
  • outside the bound
  • exact estimate f^=f\hat f = f
  • f+εNf + \varepsilon N
Sketch
Variant
128
4
Data
1.10
Bound εN\varepsilon N with ε=e/w\varepsilon = e/w1062
Items outside the bound0.0 % (guarantee: ≤ 1.8 %)
Maximum observed error400
Mean relative error, top 106.0 %
Mean relative error, items with f≤5f \le 51590 %
Exact estimates0 %
Memory: sketch counters / exact counters512 / 1000
Heavy items (orange) have mean relative error 6.0%, but items with f≤5f \le 5 have mean relative error 1590%: cell noise, of order N/wN/w, does not depend on how rare the item is.
A thousand elements with Zipf frequencies (fx∝x−sf_x \propto x^{-s}, 50 000 occurrences) pass through a sketch of w×dw \times d counters. Each point is an element: true frequency horizontal and estimated vertical, both log scale; diagonal is perfect estimate and dashed red line bound f+εNf + \eps N. The ten most frequent (orange) hug the diagonal and rare items float above a horizontal noise floor of order N/wN/w (slightly below because the minimum of dd rows is taken): the same absolute error is huge relatively. Change ww: the floor rises and falls. Increase dd: the floor drops somewhat, less than doubling ww. Try conservative update, which never worsens count-min, and Count Sketch with the same memory. Then move exponent ss: with little skew Count Sketch has much less error, but with ss above about 1.2, count-min’s minimum avoids heavy collisions and estimates rare items better.

Two practical count-min improvements:

  • Conservative update (Estan and Varghese, 2002). On insertion xx, increment only cells equal to current minimum f^x\hat f_x, up to f^x+1\hat f_x + 1. Each cell remains between the frequency of any element hashing to it and its ordinary count-min value, so estimates remain overestimates with the same guarantee and improve substantially in practice. But linearity is lost: deletion is unsupported, and the sum of two conservative sketches remains a valid bound but is no longer the joint stream’s conservative sketch, so some benefit is lost on merging.
  • Heavy hitters with count-min. Alongside the sketch maintain a heap of candidates with estimates above ϕn\phi n. Since f^x≥fx\hat f_x \ge f_x, none with fx≥ϕnf_x \ge \phi n is missed, and false candidates have fx≥(ϕ−ε)nf_x \ge (\phi - \eps) n with probability 1−δ1 - \delta. The log lab uses this.

Count Sketch: random signs and median

Count Sketch (Charikar, Chen and Farach-Colton, 2002) adds a sign function gr:U→{−1,+1}g_r : U \to \{-1, +1\} to each row, independent of hrh_r. Update (x,Δ)(x, \Delta) adds gr(x) Δg_r(x)\,\Delta to C[r,hr(x)]C[r, h_r(x)] and each row’s estimate is gr(x) C[r,hr(x)]g_r(x)\, C[r, h_r(x)]. Expanding,

gr(x) C[r,hr(x)]=fx+∑y≠xgr(x)gr(y) 1[hr(y)=hr(x)] fy.g_r(x)\, C[r, h_r(x)] = f_x + \sum_{y \ne x} g_r(x) g_r(y)\, \ind[h_r(y) = h_r(x)]\, f_y .

If grg_r is pairwise independent, E[gr(x)gr(y)]=0\E[g_r(x) g_r(y)] = 0 for y≠xy \ne x and the estimate is unbiased: noise no longer accumulates but cancels in expectation. Its variance, with hrh_r also pairwise independent, is

Var⁡=∑y≠xfy2P(hr(y)=hr(x))≤∥f∥22w,\Var = \sum_{y \ne x} f_y^2 \Pr\big(h_r(y) = h_r(x)\big) \le \frac{\norm{\vb{f}}_2^2}{w},

because cross terms have zero expectation. By Chebyshev, with w=⌈3/ε2⌉w = \lceil 3/\eps^2\rceil each row errs by more than ε∥f∥2\eps\norm{\vb{f}}_2 with probability at most 1/31/3. To move from 1/31/3 to δ\delta the minimum does not work (errors have both signs): take the median of dd rows.

Proof

If the median is outside [Q−t,Q+t][Q - t, Q + t], at least half the YrY_r are outside on the same side. Let X=∑r1[∣Yr−Q∣>t]X = \sum_r \ind[\abs{Y_r - Q} > t] be a sum of dd independent indicators with mean μ≤d/3\mu \le d/3. By Hoeffding’s bound (the additive version of Chernoff), P(X≥d/2)≤P(X−μ≥d/6)≤e−2d(1/6)2=e−d/18\Pr(X \ge d/2) \le \Pr(X - \mu \ge d/6) \le e^{-2d(1/6)^2} = e^{-d/18}.

∎

This is probability amplification again: an estimator correct with constant probability becomes one correct with probability 1−δ1 - \delta using O(log⁡(1/δ))\bigO(\log(1/\delta)) independent copies. The theorem’s constants are pessimistic; in practice 5 or 7 rows suffice.

Which is better? Count Sketch guarantees ε∥f∥2\eps\norm{\vb{f}}_2 with O(1/ε2)\bigO(1/\eps^2) columns and count-min guarantees ε∥f∥1\eps\norm{\vb{f}}_1 with O(1/ε)\bigO(1/\eps). Always ∥f∥2≤∥f∥1\norm{\vb{f}}_2 \le \norm{\vb{f}}_1, and the difference is small only when nearly all mass is in a handful of elements: with f\vb{f} uniform on UU elements, ∥f∥2=∥f∥1/U\norm{\vb{f}}_2 = \norm{\vb{f}}_1/\sqrt{U}, and in the lab cell with one million occurrences from a Zipf law of exponent 1.1 on 10510^5 elements, ∥f∥2≈164 000\norm{\vb{f}}_2 \approx 164\,000 versus ∥f∥1=106\norm{\vb{f}}_1 = 10^6. At equal memory, Count Sketch has lower mean error there, especially for frequent elements, and is unbiased; count-min is simpler, never underestimates and has a distribution-independent bound. With strong skew the balance reverses for rare items: the minimum of dd rows often finds one where xx shares no cell with a heavy item, whereas Count Sketch’s median still sees those collisions, and count-min has less error (Cormode and Muthukrishnan analyzed this Zipf regime in 2005). The figure shows this by moving the exponent.

Linear sketches and random projections

Count-min and Count Sketch are linear: the sketch is Sf\mat{S}\vb{f} for a random matrix S\mat{S} of wdwd rows and UU columns that is not stored (hash functions define it). Each column of S\mat{S} has one nonzero element per block of ww rows, equal to 1 or ±1\pm 1. Linearity gives turnstile updates, stream differences S(f−f′)=Sf−Sf′\mat{S}(\vb{f} - \vb{f}') = \mat{S}\vb{f} - \mat{S}\vb{f}' and merging for free. It is the same idea as the Johnson–Lindenstrauss lemma: a random low-dimensional projection preserves what matters. Indeed, ∑jC[r,j]2\sum_j C[r, j]^2 in one Count Sketch row is an unbiased estimator of F2=∥f∥22F_2 = \norm{\vb{f}}_2^2 (if grg_r is four-wise independent, variance is controlled as in the Alon–Matias–Szegedy sketch), and Count Sketch matrices are used as sparse projections in numerical linear algebra matrix sketching.

Counting distinct items: Flajolet–Martin to HyperLogLog

Flip a coin until heads and record the number of flips. If told that the record over a series was 20 flips, suspect around 2202^{20} rounds: a record of rr has probability order 2−r2^{-r} per round. HyperLogLog applies this idea to a hash.

Let hh hash each element to a bit string behaving uniformly, and let ρ(x)\rho(x) be the position of the first 1 in h(x)h(x), counting from 1. Then P(ρ(x)≥r)=2−(r−1)\Pr(\rho(x) \ge r) = 2^{-(r-1)}: r−1r - 1 leading zeros are needed. Crucially, duplicates do not matter: a repeated element has the same hash and ρ\rho. If the stream has nn distinct items and M=max⁡xρ(x)M = \max_x \rho(x),

P(M<r)=(1−2−(r−1))n≈exp⁡(−n 2−(r−1)),\Pr(M < r) = \big(1 - 2^{-(r-1)}\big)^n \approx \exp\big(-n\,2^{-(r-1)}\big),

which goes from near 0 to near 1 when rr crosses log⁡2n\log_2 n. Thus 2M2^M estimates nn up to a constant factor. This is the Flajolet–Martin (1985) principle. It has two problems: 2M2^M takes only powers of 2 and has huge variance (one lucky element doubles the estimate).

The solution is stochastic averaging: the first pp hash bits select one of m=2pm = 2^p registers and the rest are used for ρ\rho. Each register MjM_j stores maximum ρ\rho among items landing in it, about n/mn/m of them, so 2Mj2^{M_j} estimates n/mn/m. The mm registers must be combined. LogLog (Durand and Flajolet, 2003) used the geometric mean and achieved typical error 1.30/m1.30/\sqrt m. HyperLogLog uses the harmonic mean, far less sensitive to abnormally large registers.

The paper’s analysis using complex analysis (Mellin transforms and poissonization) proves EE asymptotically unbiased apart from a tiny oscillation, with typical relative error βm/m\beta_m/\sqrt m, with βm→3ln⁡2−1≈1.039\beta_m \to \sqrt{3\ln 2 - 1} \approx 1.039. This gives rule 1.04/m1.04/\sqrt m: with m=214m = 2^{14} registers, 0.81%. We do not reproduce the proof; the lab checks it empirically. Memory also has a nice interpretation: a register stores a number of order log⁡2n\log_2 n, fitting in log⁡2log⁡2n\log_2\log_2 n bits (hence the name). With a 64-bit hash and p=14p = 14, ρ≤51\rho \le 51 and 6 bits suffice: 214⋅6/8=12 2882^{14} \cdot 6 / 8 = 12\,288 bytes count up to 2642^{64} elements with typical error 0.81%.

InteractiveHyperLogLog registers
32-bit hash of the last item: 6 register bits (orange), leading zeros (red) and first 1 (magenta)
11001100000110101011100100100001
New IP 15.127.198.20: register j=51j = 51, ρ=6\rho = 6. The register was already 8 ≥ρ\ge \rho: it does not change.
The 64 registers MjM_j (color = value, current maximum 14)
Estimate versus true distinct count
  • HyperLogLog
  • true value ± 2 standard errors
Relative error across 300 sets of 10,000 distinct items (%)
  • HyperLogLog
  • normal, σ = 1.04/√m
Registers
Number of registers m=2pm = 2^p
Stream
item 30.0 k of 30.0 k
Distinct IPs (exact)18.1 k
HyperLogLog estimate19.5 k
Relative error+7.5 %
Zero registers (VV) and estimator0 · harmonic mean
Typical error: 1.04/m1.04/\sqrt{m} / measured13.0 % / 13.8 %
Memory64 × 5 bits = 40 bytes
Normal regime: harmonic mean of 2−Mj2^{-M_j}. Typical error is 1.04/m=13.0 %1.04/\sqrt{m} = 13.0\,\%; quadrupling mm halves it.
A stream of 30 000 IP addresses, 40% repeated. Above, the latest element’s 32-bit hash: pp orange bits choose the register, red zeros count and the first 1 (magenta) fixes ρ\rho. Play: initial steps advance individually (watch a repeated IP), then accelerate as registers warm up. Bottom left, estimate versus truth with ±2\pm 2 typical-error band; disable correction and return to the start: with few elements the harmonic mean sticks near 0.7 m0.7\,m. Right, relative error over 300 sets of 10 000 elements versus a bell of deviation 1.04/m1.04/\sqrt m: multiply mm by 4 and the bell halves in width.

Corrections

The raw formula fails at extremes, and corrections are part of the algorithm.

Small cardinalities. If nn is small relative to mm, most registers remain 0 and each contributes 20=12^0 = 1 to the sum: with all at 0, E=αmmE = \alpha_m m, about 0.72 m0.72\,m, even with nothing seen. But in this regime a better estimator is linear counting (Whang, Vander-Zanden and Taylor, 1990): if VV registers are zero, since each avoids the nn elements with probability (1−1/m)n≈e−n/m(1 - 1/m)^n \approx e^{-n/m}, E[V]≈me−n/m\E[V] \approx m e^{-n/m} and solving gives

n^=mln⁡mV.\hat n = m \ln\frac{m}{V}.

The paper’s rule: if E≤52mE \le \frac{5}{2} m and V>0V > 0, return linear counting.

Large cardinalities. With a 32-bit hash, when nn approaches 2322^{32} hashes of distinct elements begin colliding, and the paper corrects with E∗=−232ln⁡(1−E/232)E^* = -2^{32}\ln(1 - E/2^{32}) if E>232/30E > 2^{32}/30. With 64 bits this practically disappears.

HyperLogLog++. Heule, Nunkesser and Hall (2013), at Google, described improvements now used by almost all implementations: 64-bit hash, empirical raw-estimator bias correction for E≤5mE \le 5m (interpolating simulation tables), an empirical threshold for switching to linear counting, and a sparse representation storing only nonzero (register, value) pairs while there are few items. Bias correction matters: just above threshold 52m\frac{5}{2}m the raw estimator overestimates by roughly 2%, measured by a lab cell.

Mergeable sketches

In a distributed system data does not pass through one place: each server, table partition and time interval has its own stream. We need to summarize each piece independently and combine summaries without returning to the data.

SketchMergeWhy it works
Bloom filterbitwise ORbits of A∪BA \cup B are the union of those of AA and BB; identical result
count-min, Count Sketchmatrix sumlinear: SfA+SfB=S(fA+fB)\mat{S}\vb{f}_A + \mat{S}\vb{f}_B = \mat{S}(\vb{f}_A + \vb{f}_B); identical result
HyperLogLogregister-wise maximummaximum of ρ\rho over A∪BA \cup B is the maximum of the two maxima; identical result
random-key samplekk smallest keys of unioneach of the kk smallest of A∪BA \cup B is among its part’s kk smallest
Misra–Griesadd counts and subtract the (k+1)(k+1)-th largesterror remains bounded by (nA+nB)/(k+1)(n_A + n_B)/(k+1)

The first three merges are exact: the result is bit-for-bit the same as processing the entire stream through one sketch. Thus these structures underpin approximate analytics at scale. Redis stores 12 KB HyperLogLog using PFADD, PFCOUNT and PFMERGE; BigQuery offers APPROX_COUNT_DISTINCT and HLL_COUNT functions based on HyperLogLog++, and Spark has approx_count_distinct; Apache DataSketches offers production-ready mergeable serializable versions of most sketches here and many others. A typical pattern stores a HyperLogLog per day and country and answers “unique users this week in Europe” by merging 7 × 27 sketches in milliseconds, impossible with exact distinct counters that cannot be added. Likewise monitoring systems use mergeable quantile sketches (KLL, t-digest, DDSketch), in the family of XGBoost’s weighted quantile sketch, allowing large-scale inference services to aggregate latency and usage statistics replica by replica.

Two cautions. First, merging requires identical hash functions and parameters (mm, kk, ww, dd, seeds). Count-min sketches with different seeds cannot be added, and counters alone do not reveal this. Second, unions merge well; intersections do not. AND of two Bloom filters is not the intersection’s filter (it has more false positives), and estimating ∣A∩B∣\abs{A \cap B} with HyperLogLog by inclusion–exclusion, ∣A∣+∣B∣−∣A∪B∣\abs{A} + \abs{B} - \abs{A \cup B}, carries error proportional to ∣A∪B∣\abs{A \cup B}, useless for a small intersection. For set similarity use MinHash, covered in corpus deduplication.

Implementation from scratch

Cells build a small sketch library with numpy. All hashes come from a specific universal family, Dietzfelbinger’s multiply, add and shift: for 32-bit keys, ha,b(x)=⌊((ax+b) mod 264)/232⌋h_{a,b}(x) = \lfloor ((a x + b) \bmod 2^{64}) / 2^{32}\rfloor with random 64-bit a,ba, b is strongly universal, and numpy uint64 arithmetic is already modulo 2642^{64}. Synthetic streams contain 10510^5 to 10610^6 elements so each cell takes seconds in the browser; on your machine with CPython you can multiply them by 10.

First, reservoir and its weighted version. The uniformity test checks not just marginal probabilities but frequency of every one of the (62)=15\binom{6}{2} = 15 possible subsets.

[ ]Reservoir sampling and its weighted versionBrowser
import numpy as np
import random
import heapq
from itertools import combinations

def reservoir(stream, k, rng):
    """Algoritmo R: muestra uniforme de k elementos de un stream de longitud desconocida."""
    R = []
    for t, x in enumerate(stream):          # x es el elemento número t + 1
        if t < k:
            R.append(x)
        else:
            j = rng.randrange(t + 1)        # uniforme en {0, ..., t}
            if j < k:                       # con probabilidad k / (t + 1)
                R[j] = x
    return R

rng = random.Random(0)
n, k, reps = 6, 2, 30000
cuenta = {S: 0 for S in combinations(range(n), k)}
for _ in range(reps):
    cuenta[tuple(sorted(reservoir(range(n), k, rng)))] += 1
esperado = reps / len(cuenta)
chi2 = sum((c - esperado) ** 2 / esperado for c in cuenta.values())
print(f"{len(cuenta)} subconjuntos de tamaño {k}: frecuencias entre {min(cuenta.values())} y {max(cuenta.values())} (esperado {esperado:.0f})")
print(f"chi cuadrado = {chi2:.1f} con {len(cuenta) - 1} grados de libertad (el 95 % de las veces queda por debajo de 23.7)")

def reservoir_ponderado(stream, k, rng):
    """Efraimidis-Spirakis (A-Res): clave u^(1/w) y se quedan las k mayores."""
    H = []
    for x, w in stream:
        clave = rng.random() ** (1.0 / w)
        if len(H) < k:
            heapq.heappush(H, (clave, x))
        elif clave > H[0][0]:
            heapq.heapreplace(H, (clave, x))
    return [x for _, x in H]

pesos = [1, 2, 3, 4]
veces = np.zeros(len(pesos))
for _ in range(20000):
    veces[reservoir_ponderado(list(enumerate(pesos)), 1, rng)[0]] += 1
print("k = 1, frecuencia de cada elemento:", np.round(veces / 20000, 3), "  w / W:", np.round(np.array(pesos) / sum(pesos), 3))

Now heavy hitters on a Zipf stream of 10510^5 elements with 99 counters. Space-Saving uses a “lazy” heap: each increment adds a new entry and stale entries are discarded when extracting the minimum.

[ ]Misra–Gries, Space-Saving and mergingBrowser
from collections import Counter

def misra_gries(stream, k):
    C = {}
    for x in stream:
        if x in C:
            C[x] += 1
        elif len(C) < k:
            C[x] = 1
        else:                                   # se cancelan k + 1 apariciones distintas
            for y in list(C):
                C[y] -= 1
                if C[y] == 0:
                    del C[y]
    return C

def space_saving(stream, k):
    C, heap = {}, []                            # montículo perezoso de (cuenta, elemento)
    for x in stream:
        if x in C:
            C[x] += 1
        elif len(C) < k:
            C[x] = 1
        else:
            while heap[0][0] != C.get(heap[0][1]):   # descarta entradas caducadas
                heapq.heappop(heap)
            c, y = heapq.heappop(heap)
            del C[y]
            C[x] = c + 1                        # hereda la cuenta del expulsado
        heapq.heappush(heap, (C[x], x))
    return C

gen = np.random.default_rng(1)
U, s, N = 10_000, 1.1, 100_000
p = 1 / np.arange(1, U + 1) ** s
p /= p.sum()
stream = gen.choice(U, size=N, p=p).tolist()
f = Counter(stream)
k = 99
mg, ss = misra_gries(stream, k), space_saving(stream, k)
err_mg = [f[x] - mg.get(x, 0) for x in f]
err_ss = [ss[x] - f[x] for x in ss]
print(f"Misra-Gries:  infraestima como mucho {max(err_mg)} (cota n/(k+1) = {N // (k + 1)}); nunca sobreestima: {min(err_mg) >= 0}")
print(f"Space-Saving: sobreestima como mucho {max(err_ss)} (cota n/k = {N / k:.0f}); nunca infraestima: {min(err_ss) >= 0}")
pesados = [x for x in f if f[x] > N / (k + 1)]
print(f"{len(pesados)} elementos con f > n/(k+1); todos tienen contador en Misra-Gries: {all(x in mg for x in pesados)}")
print("   x      f     MG     SS")
for x, c in f.most_common(5):
    print(f"{x:4d} {c:6d} {mg.get(x, 0):6d} {ss.get(x, 0):6d}")

def fusionar_mg(A, B, k):
    C = Counter(A) + Counter(B)
    if len(C) <= k:
        return dict(C)
    resta = sorted(C.values(), reverse=True)[k]        # la (k+1)-ésima mayor cuenta
    return {x: c - resta for x, c in C.items() if c > resta}

M = fusionar_mg(misra_gries(stream[: N // 2], k), misra_gries(stream[N // 2:], k), k)
print(f"fusión de las dos mitades: {len(M)} contadores, error máximo {max(f[x] - M.get(x, 0) for x in f)} (cota {N // (k + 1)})")

Misra–Gries underestimates all top positions by the same amount, decrement-step count DD, here well below bound n/(k+1)=1000n/(k+1) = 1000; Space-Saving gets top items exactly because it never evicted them. Merging preserves the bound.

A Bloom filter sized for 1% with 10510^5 keys and three ways to choose positions:

[ ]Bloom filter with universal hashingBrowser
import sys

class MultiplyAddShift:
    """h(x) = ((a x + b) mod 2^64) >> 32 para claves de 32 bits: familia fuertemente universal."""
    def __init__(self, gen):
        self.a, self.b = gen.integers(0, 2**64, size=2, dtype=np.uint64)     # a, b uniformes de 64 bits
    def __call__(self, x):
        x = np.asarray(x, dtype=np.uint64)
        return (self.a * x + self.b) >> np.uint64(32)          # en [0, 2^32)

def a_rango(h, m):
    return (h * np.uint64(m)) >> np.uint64(32)                 # [0, 2^32) -> [0, m) sin módulo

class Bloom:
    def __init__(self, m, k, gen, modo="independientes"):
        self.m, self.k, self.modo = m, k, modo
        self.bits = np.zeros(m, dtype=bool)                    # un byte por bit, por claridad
        self.h = [MultiplyAddShift(gen) for _ in range(max(k, 2))]
    def posiciones(self, x):
        if self.modo == "independientes":
            return [a_rango(h(x), self.m) for h in self.h[: self.k]]
        g1 = a_rango(self.h[0](x), self.m)
        if self.modo == "doble":                               # Kirsch-Mitzenmacher: g1 + i g2
            g2 = 1 + a_rango(self.h[1](x), self.m - 1)
            return [(g1 + np.uint64(i) * g2) % np.uint64(self.m) for i in range(self.k)]
        return [(g1 + np.uint64(i)) % np.uint64(self.m) for i in range(self.k)]   # consecutivas: mal
    def add(self, x):
        for pos in self.posiciones(x):
            self.bits[pos] = True
    def contiene(self, x):
        r = np.ones(np.shape(x), dtype=bool)
        for pos in self.posiciones(x):
            r &= self.bits[pos]
        return r

def dimensionar(n, p):
    m = int(np.ceil(-n * np.log(p) / np.log(2) ** 2))
    return m, max(1, round(m / n * np.log(2)))

gen = np.random.default_rng(2)
n, objetivo = 100_000, 0.01
m, kb = dimensionar(n, objetivo)
claves = gen.permutation(np.unique(gen.integers(0, 2**32, size=3 * n, dtype=np.uint64)))[: 2 * n]   # 2n claves distintas
dentro, fuera = claves[:n], claves[n:]
print(f"n = {n}, objetivo {objetivo}: m = {m} bits ({m / 8 / 1024:.0f} KiB, {m / n:.2f} bits por clave), k = {kb}")
for modo in ["independientes", "doble", "consecutivas"]:
    B = Bloom(m, kb, gen, modo)
    B.add(dentro)
    assert B.contiene(dentro).all()                            # nunca hay falsos negativos
    print(f"  {modo:15s} falsos positivos {B.contiene(fuera).mean():.4f}   (teoría {(1 - np.exp(-kb * n / m)) ** kb:.4f})")
conjunto = set(dentro.tolist())
bytes_set = sys.getsizeof(conjunto) + sum(sys.getsizeof(x) for x in conjunto)
print(f"memoria: set de Python {bytes_set / 2**20:.1f} MiB frente a {m / 8 / 2**10:.0f} KiB del filtro con los bits empaquetados")

Count-min and Count Sketch on a million occurrences of 10510^5 Zipf-distributed elements. Count-min receives the stream in ten blocks, showing block processing equals processing one by one (it is linear):

[ ]Count-min and Count SketchBrowser
gen = np.random.default_rng(3)
U, s, N = 100_000, 1.1, 1_000_000
p = 1 / np.arange(1, U + 1) ** s
p /= p.sum()
stream = gen.choice(U, size=N, p=p).astype(np.uint64)
f = np.bincount(stream.astype(np.int64), minlength=U)

class CountMin:
    def __init__(self, w, d, gen):
        self.w, self.d = w, d
        self.h = [MultiplyAddShift(gen) for _ in range(d)]
        self.C = np.zeros((d, w), dtype=np.int64)
    def _col(self, r, xs):
        return a_rango(self.h[r](xs), self.w).astype(np.int64)
    def update(self, xs):
        for r in range(self.d):
            self.C[r] += np.bincount(self._col(r, xs), minlength=self.w)
    def query(self, xs):
        return np.min([self.C[r, self._col(r, xs)] for r in range(self.d)], axis=0)
    def merge(self, otro):
        self.C += otro.C                                     # mismas funciones hash: basta sumar

class CountSketch(CountMin):
    def __init__(self, w, d, gen):
        super().__init__(w, d, gen)
        self.g = [MultiplyAddShift(gen) for _ in range(d)]   # signos, independientes de las columnas
    def _signo(self, r, xs):
        return 1 - 2 * (self.g[r](xs) >> np.uint64(31)).astype(np.int64)
    def update(self, xs):
        for r in range(self.d):
            self.C[r] += np.bincount(self._col(r, xs), weights=self._signo(r, xs), minlength=self.w).astype(np.int64)
    def query(self, xs):
        return np.median([self._signo(r, xs) * self.C[r, self._col(r, xs)] for r in range(self.d)], axis=0)

eps, delta = 1e-3, 1e-2
w, d = int(np.ceil(np.e / eps)), int(np.ceil(np.log(1 / delta)))
cm = CountMin(w, d, gen)
for bloque in np.array_split(stream, 10):
    cm.update(bloque)
cs = CountSketch(w, d, gen)
cs.update(stream)
xs = np.arange(U, dtype=np.uint64)
e_cm, e_cs = cm.query(xs) - f, cs.query(xs) - f
print(f"w = {w}, d = {d}: {w * d} contadores frente a {U} elementos del universo")
print(f"count-min:    error mínimo {e_cm.min()} (nunca infraestima), medio {e_cm.mean():.1f}, máximo {e_cm.max()}")
print(f"              fracción con error > eps N = {eps * N:.0f}: {np.mean(e_cm > eps * N):.4f} (garantía: <= {delta})")
print(f"Count Sketch: error medio {e_cs.mean():+.2f} (insesgado), |error| medio {np.abs(e_cs).mean():.1f}, máximo {np.abs(e_cs).max():.0f}")
print(f"||f||_1 = {N}, ||f||_2 = {np.sqrt((f.astype(float) ** 2).sum()):.0f}")
top = np.argsort(-f)[:10]
raros = np.where((f > 0) & (f <= 5))[0]
for nombre, e in [("count-min", e_cm), ("Count Sketch", e_cs)]:
    print(f"{nombre:13s} error relativo medio: 10 más frecuentes {np.mean(np.abs(e[top]) / f[top]):.3%}, elementos con f <= 5 {np.mean(np.abs(e[raros]) / f[raros]):.0%}")

The count-min guarantee holds with enormous slack: the theorem allows 1% of elements to exceed εN=1000\eps N = 1000 while observed maximum error is a few hundred because Markov’s bound is pessimistic. Relative error for elements with f≤5f \le 5 is thousands of percent in both sketches: the figure’s noise floor. Count Sketch has lower mean error but higher maximum error because its tails extend both ways.

Finally HyperLogLog with a 64-bit hash. For first-1 position use the bit length of the remaining 64−p64 - p bits, given exactly by np.frexp because these numbers have fewer than 53 bits and are represented without rounding in float64.

[ ]HyperLogLog with corrections and mergingBrowser
def splitmix64(x):
    """Hash de 64 bits (finalizador de SplitMix64) vectorizado: una biyección de uint64."""
    z = np.asarray(x, dtype=np.uint64) + np.uint64(0x9E3779B97F4A7C15)
    z = (z ^ (z >> np.uint64(30))) * np.uint64(0xBF58476D1CE4E5B9)
    z = (z ^ (z >> np.uint64(27))) * np.uint64(0x94D049BB133111EB)
    return z ^ (z >> np.uint64(31))

class HyperLogLog:
    def __init__(self, p=14):
        self.p, self.m = p, 1 << p
        self.M = np.zeros(self.m, dtype=np.uint8)
        self.alpha = 0.7213 / (1 + 1.079 / self.m)
    def add_hashes(self, h):
        q = 64 - self.p
        j = (h >> np.uint64(q)).astype(np.int64)                     # p bits altos: el registro
        resto = h & np.uint64((1 << q) - 1)                          # los 64 - p bits restantes
        rho = q - np.frexp(resto.astype(np.float64))[1] + 1          # posición del primer 1
        np.maximum.at(self.M, j, rho.astype(np.uint8))
    def add(self, xs):
        self.add_hashes(splitmix64(xs))
    def estimate(self, corregir=True):
        E = self.alpha * self.m ** 2 / np.sum(2.0 ** -self.M.astype(float))
        V = int(np.sum(self.M == 0))
        if corregir and E <= 2.5 * self.m and V > 0:
            return self.m * np.log(self.m / V)                       # conteo lineal
        return E
    def merge(self, otro):
        self.M = np.maximum(self.M, otro.M)

gen = np.random.default_rng(11)
# enteros aleatorios de 62 bits: con n = 10^6, la probabilidad de que dos coincidan es menor que n^2 / 2^63 < 10^-6
print("       n   estimación    error   sin corrección")
for n in [10, 100, 1_000, 10_000, 100_000, 1_000_000]:
    xs = gen.integers(0, 2**62, size=n)
    H = HyperLogLog(14)
    H.add(np.concatenate([xs, xs[: n // 2]]))                          # con repeticiones
    e = H.estimate()
    print(f"{n:8d} {e:12.0f} {e / n - 1:+8.2%} {H.estimate(False) / n - 1:+16.1%}")

errores = []
for _ in range(40):
    H = HyperLogLog(10)
    H.add(gen.integers(0, 2**62, size=50_000))
    errores.append(H.estimate() / 50_000 - 1)
print(f"m = 1024, 40 repeticiones con n = 50 000: desviación típica {np.std(errores):.4f}; teoría 1.04/sqrt(m) = {1.04 / 32:.4f}")

todos = gen.integers(0, 2**62, size=1_000_000)
A, B = HyperLogLog(14), HyperLogLog(14)
A.add(todos[:600_000])
B.add(todos[400_000:])
nA, nB = A.estimate(), B.estimate()
A.merge(B)
print(f"unión fusionada: {A.estimate():.0f} (real 1 000 000); intersección por inclusión-exclusión: {nA + nB - A.estimate():.0f} (real 200 000)")
print(f"memoria: {A.m} registros de 6 bits = {A.m * 6 // 8} bytes")

Without correction, with 10 elements the raw estimate exceeds ten thousand: the 0.72 m≈11 8000.72\,m \approx 11\,800 of empty registers. With correction, error is small throughout. Merging two 600 000-element sketches gives the union with usual typical error, but inclusion–exclusion intersection inherits errors of the three terms, about 4900, 4900 and 8100 (0.81 %0.81\,\% of 6×1056\times 10^5, 6×1056\times 10^5 and 10610^6). Since sketches share elements, errors partly cancel: across 30 seeds, intersection-error standard deviation is about 5000, 2.5% of 200 000. This run had error about 2000, 1%, with some luck. The serious issue is that error scales with set sizes, not intersection size: with intersection 2000 it would still be thousands, larger than the intersection itself.

The final cell measures raw-estimator bias just above the threshold, the reason for HyperLogLog++ correction. With m=1024m = 1024 threshold 52m\frac{5}{2}m is 2560:

[ ]Bias in the intermediate regionBrowser
gen = np.random.default_rng(22)
reps = 300
print("    n    n/m   error medio   desviación   usa conteo lineal")
for n in [1500, 2300, 2500, 2700, 3000, 3500, 4000, 5000, 8000]:
    e, lineal = [], 0
    for _ in range(reps):
        H = HyperLogLog(10)
        H.add(gen.integers(0, 2**62, size=n))
        e.append(H.estimate() / n - 1)
        lineal += H.estimate() != H.estimate(corregir=False)
    print(f"{n:5d} {n / 1024:6.2f} {np.mean(e):+11.2%} {np.std(e):11.2%} {lineal / reps:14.0%}")
print(f"(error estándar de cada media: unos {0.03 / np.sqrt(reps):.2%})")

Far from the threshold both estimators are nearly unbiased: linear counting on the left and harmonic mean from roughly 4m4m. In between, not so. With n≈2.4 mn \approx 2.4\,m, in some runs raw estimate falls below 52m\frac{5}{2}m and linear counting wins; in others it exceeds it and harmonic mean wins, overestimating in that region: mean rises about 1.4% and deviation grows. Just above, with n≈2.6 mn \approx 2.6\,m, harmonic mean overestimates by nearly 2% on average, over half its own 3.25% typical error; bias falls to a few tenths near 4m4m and vanishes near 5m5m. A simulation with 8000 repetitions per point (standard error about 0.04 percentage points) gives +0.2 %+0.2\,\%, +1.4 %+1.4\,\%, +1.9 %+1.9\,\%, +1.2 %+1.2\,\%, +0.6 %+0.6\,\% and +0.2 %+0.2\,\% for n/m=2.25n/m = 2.25, 2.442.44, 2.642.64, 2.932.93, 3.423.42 and 3.913.91, and +0.04 %+0.04\,\% for 4.884.88. HyperLogLog++ subtracts that bias using a simulation table.

Streaming log analysis

Now a complete problem: a synthetic 300 000-request web log with three columns (IP, route and status code), read in chunks of 10 000 lines as if arriving over the network. One pass produces distinct IPs with HyperLogLog, most frequent routes with count-min and candidates, and a uniform 1000-line sample using random keys. Strings become integers with pd.util.hash_array, pandas’ vectorized 64-bit hash. Finally pandas calculates exact answers.

[ ]One pass over an access logBrowser
import pandas as pd

gen = np.random.default_rng(5)
n_ips, n_rutas, N = 50_000, 300, 300_000
ips = np.array([f"{a}.{b}.{c}.{d}" for a, b, c, d in gen.integers(1, 255, size=(n_ips, 4))])
rutas = np.array([f"/api/recurso/{i}" for i in range(n_rutas)])
actividad = gen.pareto(1.2, n_ips) + 1                       # unas pocas IP generan mucho tráfico
p_ruta = 1 / np.arange(1, n_rutas + 1) ** 1.05
log = pd.DataFrame({
    "ip": ips[gen.choice(n_ips, size=N, p=actividad / actividad.sum())],
    "ruta": rutas[gen.choice(n_rutas, size=N, p=p_ruta / p_ruta.sum())],
    "estado": gen.choice([200, 304, 404, 500], size=N, p=[0.86, 0.08, 0.05, 0.01]),
})

def hash64(col):
    return pd.util.hash_array(col.to_numpy())                    # uint64

def resumir(trozos, semilla):
    """Una pasada: HLL de IP, count-min de rutas con candidatos y muestra bottom-k."""
    hll = HyperLogLog(12)
    cm = CountMin(2048, 5, np.random.default_rng(6))             # semilla fija: sketches fusionables
    candidatos, k_muestra, vistos = {}, 1000, 0
    claves, muestra = np.empty(0), log.iloc[:0]
    g = np.random.default_rng(semilla)
    for trozo in trozos:
        vistos += len(trozo)
        hll.add_hashes(hash64(trozo["ip"]))
        h32 = hash64(trozo["ruta"]) & np.uint64(0xFFFFFFFF)       # claves de 32 bits para el count-min
        cm.update(h32)
        rutas_t, idx = np.unique(trozo["ruta"].to_numpy(), return_index=True)
        for r, e, h in zip(rutas_t, cm.query(h32[idx]), h32[idx]):
            if e >= 0.005 * vistos:                              # candidata: más del 0.5 % de lo visto
                candidatos[r] = h
        claves = np.concatenate([claves, g.random(len(trozo))])  # claves aleatorias: se quedan las k menores
        muestra = pd.concat([muestra, trozo])
        sel = np.argsort(claves)[:k_muestra]
        claves, muestra = claves[sel], muestra.iloc[sel]
    return hll, cm, candidatos, muestra

trozos = [log.iloc[i:i + 10_000] for i in range(0, N, 10_000)]
hll, cm, cand, muestra = resumir(trozos, 7)

exacto = log["ip"].nunique()
print(f"IP distintas: HyperLogLog {hll.estimate():.0f}, exacto {exacto} ({hll.estimate() / exacto - 1:+.2%}; error típico {1.04 / 64:.1%})")
vc = log["ruta"].value_counts()
est = {r: cm.query(np.array([h], dtype=np.uint64))[0] for r, h in cand.items()}
top = sorted(est, key=est.get, reverse=True)[:6]
print(f"\n{'ruta':16s} {'count-min':>9s} {'exacto':>7s}")
for r in top:
    print(f"{r:16s} {est[r]:9d} {vc[r]:7d}")
print("las 6 más frecuentes coinciden con las exactas:", top == list(vc.index[:6]))
print("\nproporción de cada código de estado:")
print(pd.DataFrame({"muestra (1000)": muestra["estado"].value_counts(normalize=True),
                    "log completo": log["estado"].value_counts(normalize=True)}).round(3).to_string())

With 300 routes and 2048 columns, count-min barely has collisions among frequent routes and estimates are exact or nearly so; HyperLogLog with 2122^{12} registers (3 KiB) differs by 2.9%, 1.8 times its 1.6% typical error (in one run a deviation that large or larger occurs about once in fourteen, a useful reminder that typical error is not a maximum); the 1000-line sample reproduces status-code proportions with expected sampling error, order 0.86⋅0.14/1000≈1.1\sqrt{0.86 \cdot 0.14/1000} \approx 1.1 points for 200. The real interest is merging: if the log came from two servers, each with its own summary, the combined result would be identical.

[ ]Two servers, one summaryBrowser
hll1, cm1, cand1, m1 = resumir(trozos[:12], 8)                  # servidor 1: 120 000 líneas
hll2, cm2, cand2, m2 = resumir(trozos[12:], 9)                  # servidor 2: 180 000 líneas
hll1.merge(hll2)
cm1.merge(cm2)
print("HLL fusionado idéntico al de una sola pasada:", np.array_equal(hll1.M, hll.M))
print("count-min fusionado idéntico:", np.array_equal(cm1.C, cm.C))
e1, e2 = log.iloc[:120_000]["ip"].nunique(), log.iloc[120_000:]["ip"].nunique()
print(f"IP distintas en la unión: HyperLogLog fusionado {hll1.estimate():.0f}, exacto {exacto}")
print(f"exactos por servidor: {e1} + {e2} = {e1 + e2}, que cuenta dos veces las {e1 + e2 - exacto} IP comunes")

Merged HyperLogLog registers and count-min counters are bit-for-bit identical to one pass: merging these two sketches is exact. Exact distinct counts from each server cannot instead be added, because IPs visiting both are counted twice; this makes mergeable sketches useful in databases.

Common mistakes

Exercises

NumericSize a Bloom filter: memory
You need a Bloom filter for n=108n = 10^8 URLs with false-positive rate 0.1%. How many megabytes (10610^6 bytes) does the bit array occupy with optimal mm?
NumericSize a Bloom filter: hashes
For the previous filter (n=108n = 10^8, p=0.1 %p = 0.1\,\%, optimal mm), how many hash functions should be used? Give the integer closest to optimum.
NumericSize a count-min sketch
How many counters total (w⋅dw \cdot d) does a count-min sketch with ε=10−3\varepsilon = 10^{-3} and δ=10−2\delta = 10^{-2} require, with w=⌈e/ε⌉w = \lceil e/\varepsilon \rceil and d=⌈ln⁡(1/δ)⌉d = \lceil \ln(1/\delta) \rceil?
NumericHyperLogLog memory
You want HyperLogLog with typical error 1.04/m1.04/\sqrt{m} at most 1%, mm a power of 2 and packed 6-bit registers. How many bytes do registers occupy?
NumericHow much Misra–Gries can underestimate
A stream of n=107n = 10^7 queries is summarized with Misra–Gries using k=999k = 999 counters. What is the largest possible frequency underestimate under the theorem?
QuizThe right structure for each question
Which question–structure assignments are correct?

More than one answer may be correct.

QuizDelete from a Bloom filter
In a standard Bloom filter with multiple inserted keys, you delete xx by clearing its kk bits. What can happen?
QuizWhat count-min says about a rare item
A count-min sketch with ε=10−3\varepsilon = 10^{-3} and δ=10−2\delta = 10^{-2} summarizes n=108n = 10^8 events. Element xx truly occurs fx=50f_x = 50 times. What does the theorem guarantee about f^x\hat f_x?
ProofThe reservoir is uniform
Prove: After processing t≥kt \ge k elements with algorithm R, reservoir RtR_t is each of the (tk)\binom{t}{k} subsets of kk positions with probability 1/(tk)1/\binom{t}{k}.
0
Induct on tt. For t=kt = k the reservoir contains the first kk positions, the sole possible subset. Assume the result for tt and fix subset SS of kk positions among {1,…,t+1}\{1, \dots, t+1\}.

Step 1 of 4. First case: t+1∉St + 1 \notin S. What is P(Rt+1=S)\Pr(R_{t+1} = S)?

ProofThe count-min guarantee
Prove: In strict turnstile (fy≥0f_y \ge 0 for every yy), with w=⌈e/ε⌉w = \lceil e/\varepsilon \rceil, d=⌈ln⁡(1/δ)⌉d = \lceil \ln(1/\delta) \rceil and functions h1,…,hdh_1, \dots, h_d independently chosen from a universal family, f^x≥fx\hat f_x \ge f_x and P(f^x>fx+ε∥f∥1)≤δ\Pr(\hat f_x > f_x + \varepsilon\|\vb{f}\|_1) \le \delta.
0
Fix xx and row rr. By linearity, C[r,hr(x)]=fx+ZrC[r, h_r(x)] = f_x + Z_r with Zr=∑y≠x1[hr(y)=hr(x)] fyZ_r = \sum_{y \neq x} \ind[h_r(y) = h_r(x)]\, f_y.

Step 1 of 4. Why f^x≥fx\hat f_x \ge f_x?

CodeHyperLogLog with 2^14 registers
Complete class HLL: add(xs) receives an integer array (possibly with duplicates), passes it through splitmix64 and updates registers; estimate() returns the HyperLogLog estimate with αm=0.7213/(1+1.079/m)\alpha_m = 0.7213/(1 + 1.079/m) and small-cardinality correction (linear counting if E≤2.5 mE \le 2.5\,m and zero registers exist). Use the high pp bits for the register and position of the first 1 among the remaining 64−p64 - p, counting from 1. Tests check relative error below 3% at several cardinalities from 500 to 600 000. Vectorize with numpy: a Python loop per element would be too slow.
import numpy as np

def splitmix64(x):
  """Hash de 64 bits vectorizado (finalizador de SplitMix64)."""
  z = np.asarray(x, dtype=np.uint64) + np.uint64(0x9E3779B97F4A7C15)
  z = (z ^ (z >> np.uint64(30))) * np.uint64(0xBF58476D1CE4E5B9)
  z = (z ^ (z >> np.uint64(27))) * np.uint64(0x94D049BB133111EB)
  return z ^ (z >> np.uint64(31))

class HLL:
  def __init__(self, p=14):
      self.p = p
      self.m = 1 << p
      self.M = np.zeros(self.m, dtype=np.uint8)

  def add(self, xs):
      """Añade un array de enteros (puede tener repeticiones)."""
      h = splitmix64(xs)
      # tu código: registro j (p bits altos), rho (primer 1 en los 64 - p bits restantes)
      # y M[j] = max(M[j], rho)

  def estimate(self):
      # tu código: media armónica con alpha_m y corrección para cardinales pequeños
      return 0.0
Shift+Enter to run

Summary

Key idea
When data passes once and does not fit in memory, a well-chosen hash turns any stream into something behaving randomly, and a sublinear summary (sample, counters, bit array or maxima) answers with bounded error and failure probability; if mergeable, the same summary also serves distributed systems.
  • The streaming model measures memory, per-item time and passes, and (ε,δ)(\eps, \delta) guarantees hold for any stream fixed before hash selection. Exact distinct counting costs UU bits: both approximation and randomness are needed.
  • Reservoir sampling maintains a uniform kk-item sample from an unknown-length stream; random keys make it mergeable, and keys u1/wu^{1/w} make it weighted.
  • Misra–Gries and Space-Saving find every element above n/(k+1)n/(k+1) (or n/kn/k) using kk counters, with error ≤n/(k+1)\le n/(k+1).
  • A Bloom filter has no false negatives and false-positive rate (1−e−kn/m)k(1 - e^{-kn/m})^k, minimized at k=(m/n)ln⁡2k = (m/n)\ln 2; target pp costs 1.44log⁡2(1/p)1.44\log_2(1/p) bits per key regardless of key size. Its hashes must be independent and it does not support deletion.
  • Count-min guarantees fx≤f^x≤fx+εnf_x \le \hat f_x \le f_x + \eps n with probability 1−δ1 - \delta using ⌈e/ε⌉×⌈ln⁡(1/δ)⌉\lceil e/\eps\rceil \times \lceil\ln(1/\delta)\rceil counters (Markov per row, independence across rows); Count Sketch is unbiased with error ε∥f∥2\eps\norm{\vb{f}}_2 (Chebyshev per row, median across rows). Both are random linear projections and their error is additive: unhelpful for rare items.
  • HyperLogLog counts distinct items with mm 6-bit registers and typical error 1.04/m1.04/\sqrt m (0.81% with 12 KiB), thanks to the harmonic mean of 2Mj2^{M_j}; small-cardinality linear counting and HyperLogLog++ bias correction are part of the algorithm.
  • Bloom (OR), count-min and Count Sketch (sum), and HyperLogLog (maximum) merge exactly with shared parameters and seeds: hence their importance to approximate analytics in databases and monitoring systems.