Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

Count-Min, HyperLogLog & Streaming Sketches

Frequency and distinct-count estimates in kilobytes.

How many distinct users visited today? A hash set of a billion IDs takes gigabytes; HyperLogLog answers to within about 1% from 12 kilobytes, and the summaries of a thousand servers merge by taking maxima. This lesson proves why such sketches work, shows what no sketch can do, and measures how close the best ones are to optimal.

What you’ll learn

  • Define the streaming model, and explain why exact answers need memory linear in the data while randomized approximations need very little.
  • Prove the Count-Min guarantee with Markov's inequality, and the Count sketch and AMS guarantees with second moments.
  • Explain how Flajolet–Martin, LogLog and HyperLogLog estimate distinct counts, and where HyperLogLog's standard error 1.04/m1.04/\sqrt m comes from.
  • State the optimal space for counting distinct elements, and use mergeability to design distributed summaries.

The streaming model

Why approximate and randomized? Suppose an algorithm counted distinct items exactly. From its memory after the stream, you could recover the whole set of items seen: run a copy of the algorithm on each possible next item yy and check whether the count goes up. A set of items from [n][n] can be any of 2n2^n sets, so the memory needs nn bits. Alon, Matias and Szegedy (1996) showed that even a deterministic algorithm needs linear space to approximate F0F_0 within a small constant factor. Randomization and approximation together bring the space down to kilobytes.

The sketches in this lesson are built from hash functions with limited independence, and most are linear: the sketch is SfS f for a random matrix SS. Linear sketches handle deletions for free and merge by addition.

Count-Min: point queries with one-sided error

The Count-Min sketch (Cormode & Muthukrishnan, 2005) keeps dd rows of ww counters and one hash function hj:[n]→[w]h_j : [n] \to [w] per row, drawn independently from a universal family. An update (i,c)(i, c) adds cc to C[j][hj(i)]C[j][h_j(i)] in every row; the estimate is f^i=min⁡jC[j][hj(i)]\hat f_i = \min_j C[j][h_j(i)].

DerivationProof
  1. E[Xj] ≤ ∥f∥1w ≤ εe ∥f∥1\E[X_j] \ \le\ \frac{\norm f_1}{w} \ \le\ \frac{\varepsilon}{e}\,\norm f_1

    One row. The counter of ii in row jj holds fif_i plus the noise Xj=∑y≠ify [hj(y)=hj(i)]≥0X_j = \sum_{y \ne i} f_y\,[h_j(y) = h_j(i)] \ge 0, since all fy≥0f_y \ge 0. Universality bounds each collision probability by 1/w1/w:

  2. Pr⁡[Xj≥ε∥f∥1] ≤ E[Xj]ε∥f∥1 ≤ 1e\Pr\big[X_j \ge \varepsilon\norm f_1\big] \ \le\ \frac{\E[X_j]}{\varepsilon\norm f_1} \ \le\ \frac1e

    Markov. Markov's inequality for the nonnegative XjX_j:

  3. Pr⁡[f^i−fi≥ε∥f∥1]=∏j=1dPr⁡[Xj≥ε∥f∥1] ≤ e−d ≤ δ\Pr\big[\hat f_i - f_i \ge \varepsilon\norm f_1\big] = \prod_{j=1}^{d}\Pr\big[X_j \ge \varepsilon\norm f_1\big] \ \le\ e^{-d} \ \le\ \delta

    Independent rows. The estimate is bad only if every row is bad, and the rows' hash functions are independent:

  4. ddc cln⁡c=ln⁡c−1ln⁡2c=0  ⟺  c=e\frac{d}{dc}\,\frac{c}{\ln c} = \frac{\ln c - 1}{\ln^2 c} = 0 \iff c = e

    Why ee? With per-row failure probability 1/c1/c the sketch needs w=c/εw = c/\varepsilon and d=ln⁡(1/δ)/ln⁡cd = \ln(1/\delta)/\ln c, so wd=cln⁡c⋅ln⁡(1/δ)εwd = \frac{c}{\ln c}\cdot\frac{\ln(1/\delta)}{\varepsilon}, and c/ln⁡cc/\ln c is smallest at c=ec = e:

python
import math, random

P = (1 << 61) - 1

class CountMin:
    def __init__(self, eps, delta):
        self.w = math.ceil(math.e / eps)
        self.d = math.ceil(math.log(1 / delta))
        self.rows = [[0] * self.w for _ in range(self.d)]
        self.ab = [(random.randrange(1, P), random.randrange(P)) for _ in range(self.d)]

    def _cols(self, x):                  # x: an integer item id
        return [((a * x + b) % P) % self.w for a, b in self.ab]

    def add(self, x, c=1):
        for row, j in zip(self.rows, self._cols(x)):
            row[j] += c

    def estimate(self, x):
        return min(row[j] for row, j in zip(self.rows, self._cols(x)))

One Carter–Wegman function per row, drawn independently. For heavy hitters, keep a min-heap of the candidates whose estimates reach φ∥f∥1\varphi\norm f_1: every item with fi≥φ∥f∥1f_i \ge \varphi\norm f_1 is reported, and an item with fi<(φ−ε)∥f∥1f_i < (\varphi - \varepsilon)\norm f_1 is wrongly reported with probability at most δ\delta.

In the turnstile model the noise XjX_j can be negative and the minimum loses its guarantee. Taking the median of the rows instead keeps the error within 3ε∥f∥13\varepsilon\norm f_1, at the price of a constant factor more rows for the same failure probability. A common practical refinement, conservative update, increments only the counters that equal the current minimum; it reduces overestimates on real data but works only for insertions.

Random signs: the Count sketch and AMS

Count-Min's noise only adds up. The Count sketch (Charikar, Chen & Farach-Colton, 2002) makes it cancel: each row jj also has a sign function sj:[n]→{−1,+1}s_j : [n] \to \{-1, +1\}, an update (i,c)(i, c) adds c sj(i)c\,s_j(i) to C[j][hj(i)]C[j][h_j(i)], and the estimate is the median over the rows of sj(i) C[j][hj(i)]s_j(i)\,C[j][h_j(i)].

DerivationCount sketch: error in terms of the 2-norm
  1. E[Yj]=fi\E[Y_j] = f_i

    Unbiased rows. Row jj reads Yj=fi+∑y≠isj(i)sj(y) fy [hj(y)=hj(i)]Y_j = f_i + \sum_{y \ne i} s_j(i)s_j(y)\,f_y\,[h_j(y) = h_j(i)]. With pairwise independent signs, independent of hjh_j, every cross term has mean zero:

  2. Var⁡[Yj]=∑y≠ify2 Pr⁡[hj(y)=hj(i)] ≤ ∥f∥22w\Var[Y_j] = \sum_{y \ne i} f_y^2\,\Pr[h_j(y) = h_j(i)] \ \le\ \frac{\norm f_2^2}{w}

    Small variance. Squaring the noise, the products of two different signs again average to zero, which leaves only squares:

  3. Pr⁡[∣Yj−fi∣>ε∥f∥2] ≤ ∥f∥22/wε2∥f∥22 ≤ 13\Pr\big[\abs{Y_j - f_i} > \varepsilon\norm f_2\big] \ \le\ \frac{\norm f_2^2/w}{\varepsilon^2\norm f_2^2} \ \le\ \frac13

    Chebyshev per row. With w=⌈3/ε2⌉w = \lceil 3/\varepsilon^2 \rceil columns, Chebyshev's inequality bounds the chance that a row errs by more than ε∥f∥2\varepsilon\norm f_2:

  4. Pr⁡[∣median⁡jYj−fi∣>ε∥f∥2] ≤ δ\Pr\Big[\big|\operatorname{median}_j Y_j - f_i\big| > \varepsilon\norm f_2\Big] \ \le\ \delta

    Median of rows. The median errs only if at least half the rows do; with d=O(log⁡(1/δ))d = O(\log(1/\delta)) independent rows, a Chernoff bound makes that probability at most δ\delta:

The trade is O(1/ε2)O(1/\varepsilon^2) columns instead of O(1/ε)O(1/\varepsilon), for an error in ∥f∥2≤∥f∥1\norm f_2 \le \norm f_1, two-sided but unbiased, that survives deletions. On skewed data the difference is dramatic: one item with frequency 1,000 among 10610^6 items with frequency 1 gives ∥f∥1=1,001,000\norm f_1 = 1{,}001{,}000 but ∥f∥2=2×106≈1,414\norm f_2 = \sqrt{2 \times 10^6} \approx 1{,}414.

The same signs estimate the second moment F2=∑ifi2F_2 = \sum_i f_i^2, which databases call the self-join size. Alon, Matias and Szegedy (1996) keep one counter Z=∑is(i)fiZ = \sum_i s(i) f_i, a single row of width 1, in a paper that founded the field and won the 2005 Gödel Prize.

DerivationThe AMS estimator of the second moment
  1. E[Z2]=∑ifi2+∑i≠jfifj E[s(i)s(j)]=F2\E[Z^2] = \sum_i f_i^2 + \sum_{i \ne j} f_i f_j\,\E[s(i)s(j)] = F_2

    Mean. Cross terms vanish under pairwise independence of the signs:

  2. E[Z4]=∑ifi4+6∑i<jfi2fj2\E[Z^4] = \sum_i f_i^4 + 6\sum_{i<j} f_i^2 f_j^2

    Fourth moment. With 4-wise independent signs, E[s(i)s(j)s(k)s(l)]\E[s(i)s(j)s(k)s(l)] is 1 when the four indices pair up and 0 otherwise. There are three ways to pair four positions:

  3. Var⁡[Z2]=4∑i<jfi2fj2 ≤ 2F22\Var[Z^2] = 4\sum_{i<j} f_i^2 f_j^2 \ \le\ 2F_2^2

    Variance. Subtract F22=∑ifi4+2∑i<jfi2fj2F_2^2 = \sum_i f_i^4 + 2\sum_{i<j} f_i^2 f_j^2:

  4. Pr⁡[∣F2^−F2∣>εF2] ≤ δwithO ⁣(ε−2log⁡1δ) counters\Pr\big[\abs{\widehat{F_2} - F_2} > \varepsilon F_2\big] \ \le\ \delta \quad\text{with}\quad O\!\left(\varepsilon^{-2}\log\tfrac1\delta\right)\ \text{counters}

    Median of means. Average O(1/ε2)O(1/\varepsilon^2) independent copies of Z2Z^2 to make Chebyshev's error probability at most 14\tfrac14, then take the median of O(log⁡(1/δ))O(\log(1/\delta)) such averages:

Counting distinct elements: from Flajolet–Martin to HyperLogLog

Duplicates are the whole difficulty of counting distinct items, and hashing removes it: equal items have equal hashes, so any statistic of the set of hash values ignores repetition. Flajolet and Martin (1985) observed that long runs of leading zeros are rare, so the longest run seen reveals the scale of the count. Their probabilistic counting refined it into an estimator with stochastic averaging over many bitmaps; LogLog (Durand & Flajolet, 2003) kept only one small maximum per register; HyperLogLog (Flajolet, Fusy, Gandouet & Meunier, 2007) changed how registers are averaged.

DerivationWhy maxima of leading zeros count
  1. Pr⁡[ρ(x)≥r]=2−(r−1)\Pr[\rho(x) \ge r] = 2^{-(r-1)}

    One item. Hash each item to a uniform bit string and let ρ(x)\rho(x) be the position of its first 1-bit, so Pr⁡[ρ(x)=r]=2−r\Pr[\rho(x) = r] = 2^{-r}:

  2. Pr⁡[R<r]=(1−2−(r−1))n≈exp⁡ ⁣(−n 2−(r−1))\Pr[R < r] = \left(1 - 2^{-(r-1)}\right)^{n} \approx \exp\!\left(-n\,2^{-(r-1)}\right)

    The maximum. For R=max⁡xρ(x)R = \max_x \rho(x) over nn distinct items, independence gives a probability near 0 when 2r≪n2^r \ll n and near 1 when 2r≫n2^r \gg n. So R=log⁡2n+O(1)R = \log_2 n + O(1), and 2R2^R estimates nn only up to a constant factor:

  3. E=αm m2(∑j=1m2−Mj)−1,αm≈0.72131+1.079/mE = \alpha_m\, m^2\Big(\sum_{j=1}^{m} 2^{-M_j}\Big)^{-1}, \qquad \alpha_m \approx \frac{0.7213}{1 + 1.079/m}

    Stochastic averaging. Use the first bb hash bits to send each item to one of m=2bm = 2^b registers, so each register sees about n/mn/m items and keeps MjM_j, the largest ρ\rho of the remaining bits. A single register with an unusually long run would dominate an arithmetic mean of 2Mj2^{M_j}, so HyperLogLog takes a harmonic mean:

  4. Var⁡[E]n ≈ 3ln⁡2−1m ≈ 1.04m\frac{\sqrt{\Var[E]}}{n} \ \approx\ \frac{\sqrt{3\ln 2 - 1}}{\sqrt m} \ \approx\ \frac{1.04}{\sqrt m}

    Accuracy. Flajolet et al. proved that EE is asymptotically unbiased, with relative standard error

python
import hashlib, math

def h64(x):
    return int.from_bytes(hashlib.blake2b(str(x).encode(), digest_size=8).digest(), 'big')

class HyperLogLog:
    def __init__(self, b=10):                  # m = 2^b registers
        self.b, self.m = b, 1 << b
        self.M = [0] * self.m

    def add(self, x):
        h = h64(x)
        j = h >> (64 - self.b)                 # first b bits pick a register
        w = h & ((1 << (64 - self.b)) - 1)     # the remaining 64 - b bits
        rho = (64 - self.b) - w.bit_length() + 1   # position of the first 1-bit
        self.M[j] = max(self.M[j], rho)

    def count(self):
        m = self.m
        E = 0.7213 / (1 + 1.079 / m) * m * m / sum(2.0 ** -r for r in self.M)
        zeros = self.M.count(0)
        if E <= 2.5 * m and zeros:             # small counts: linear counting
            E = m * math.log(m / zeros)
        return E

With m=1024m = 1024 registers, repeated runs on 100,000 distinct items gave a root-mean-square relative error of about 3.2%, matching 1.04/1024≈3.25%1.04/\sqrt{1024} \approx 3.25\%. Below 2.5m2.5m the estimator switches to linear counting on the number of empty registers, which is more accurate for small counts.

Predict before you look

About how many HyperLogLog registers do you need for a standard error of 1%?

Show the answer

10816 registers

Solve 1.04/m=0.011.04/\sqrt m = 0.01: m=(1.04/0.01)2=1042=10,816m = (1.04/0.01)^2 = 104^2 = 10{,}816. Implementations round to a power of two, 214=16,3842^{14} = 16{,}384, for 0.81%: the 12-kilobyte configuration with 6-bit registers.

Merging, practice and the frontier

SummaryMerge ruleDeletions
Bloom filterbitwise OR (same mm, same hash functions)no
Count-Min sketchadd the arrays (same hash functions)yes, with the median estimator
Count sketch, AMSadd the arrays (linear sketches)yes
HyperLogLogregister-wise maximumno
Misra–Gries heavy hittersadd the counters, then subtract the (k+1)(k+1)-st largest countno
A summary is mergeable if merging two summaries yields a summary of the combined data with the same size and error guarantee (Agarwal, Cormode, Huang, Phillips, Wei & Yi, 2012). Linear sketches are mergeable by construction; for Misra–Gries and quantile summaries it takes a proof.
Check your understanding

Servers A and B each keep a HyperLogLog of the user IDs they saw today, with the same hash function and the same mm. Some users visited both. How do you get the number of distinct users overall?

  1. Add the two estimates
  2. Average the two register arrays, then estimate
  3. Take the register-wise maximum of the two arrays, then estimate
  4. Add the two register arrays, then estimate
Show the answer

C. Take the register-wise maximum of the two arrays, then estimate

Each register stores the maximum ρ\rho over the hashes routed to it, and the maximum over the union of two sets is the maximum of the two maxima. The merged array is exactly the sketch that one server would have built from both streams, so users seen by both are counted once.

Sketches are infrastructure now. Redis's PFCOUNT is a HyperLogLog with 2142^{14} registers (12 KB, standard error 0.81%); many SQL engines offer approximate distinct counts; Google's HyperLogLog++ (Heule, Nunkesser & Hall, 2013) added 64-bit hashing, empirical bias correction and a sparse representation for small counts; network monitors track heavy flows with Count-Min; and open-source libraries such as Apache DataSketches package mergeable sketches for distinct counts, frequencies and quantiles.

Key takeaways

  • Counting distinct items exactly needs memory linear in the universe, and deterministic approximation is not much cheaper; randomized (ε,δ)(\varepsilon,\delta)-approximations need only kilobytes.
  • Count-Min: width ⌈e/ε⌉\lceil e/\varepsilon\rceil, depth ⌈ln⁡(1/δ)⌉\lceil\ln(1/\delta)\rceil, never underestimates, and overestimates by more than ε∥f∥1\varepsilon\norm f_1 with probability at most δ\delta (Markov in each row, independence across rows).
  • Random signs make estimates unbiased: the Count sketch has error ε∥f∥2\varepsilon\norm f_2 with O(1/ε2)O(1/\varepsilon^2) columns, and AMS estimates F2F_2 with Var⁡[Z2]≤2F22\Var[Z^2] \le 2F_2^2 from 4-wise independent signs.
  • HyperLogLog keeps the longest leading-zero run per register and combines registers by a harmonic mean, for standard error about 1.04/m1.04/\sqrt m; Kane, Nelson and Woodruff (2010) achieved the optimal O(ε−2+log⁡n)O(\varepsilon^{-2} + \log n) bits.
  • Linear sketches merge by addition and HyperLogLogs by register-wise maxima, so each machine summarizes its own data and the summaries combine exactly.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

In the Count-Min proof, what role does the constant ee in the width w=⌈e/ε⌉w = \lceil e/\varepsilon \rceil play?

  1. It makes each row's estimate unbiased
  2. It is required for Markov's inequality to apply
  3. It makes each row fail with probability at most 1/e1/e, and that choice minimizes the total number of counters w⋅dw \cdot d
  4. It is the base of the logarithm in the number of distinct items
Show the answer

C. It makes each row fail with probability at most 1/e1/e, and that choice minimizes the total number of counters w⋅dw \cdot d

Markov gives per-row failure ≤1/c\le 1/c for width c/εc/\varepsilon, and ⌈ln⁡(1/δ)/ln⁡c⌉\lceil\ln(1/\delta)/\ln c\rceil independent rows then fail together with probability at most δ\delta. The product wd∝c/ln⁡cwd \propto c/\ln c is minimized at c=ec = e. Any constant c>1c > 1 would work, with more counters.

Question 2

The AMS estimator Z=∑is(i)fiZ = \sum_i s(i) f_i of F2=∑ifi2F_2 = \sum_i f_i^2 uses random signs s(i)=±1s(i) = \pm1. Where is 4-wise independence of the signs needed?

  1. To make E[Z2]=F2\E[Z^2] = F_2
  2. To bound Var⁡[Z2]≤2F22\Var[Z^2] \le 2F_2^2, which involves E[Z4]\E[Z^4] and hence products of four signs
  3. To make ZZ an integer
  4. It is not needed: pairwise independence gives the same guarantee
Show the answer

B. To bound Var⁡[Z2]≤2F22\Var[Z^2] \le 2F_2^2, which involves E[Z4]\E[Z^4] and hence products of four signs

The mean needs only E[s(i)s(j)]=0\E[s(i)s(j)] = 0 for i≠ji \ne j, which pairwise independence provides. The variance needs E[s(i)s(j)s(k)s(l)]=0\E[s(i)s(j)s(k)s(l)] = 0 unless the indices pair up, a property of 4-wise independence; it yields Var⁡[Z2]=4∑i<jfi2fj2≤2F22\Var[Z^2] = 4\sum_{i<j}f_i^2f_j^2 \le 2F_2^2.

Question 3

Why does HyperLogLog combine its registers with a harmonic mean of 2−Mj2^{-M_j} rather than an arithmetic mean of 2Mj2^{M_j}?

  1. A single register with an unusually large maximum would dominate an arithmetic mean of 2Mj2^{M_j}; the harmonic mean damps such outliers
  2. The harmonic mean is cheaper to compute
  3. The harmonic mean makes the estimate exact for small counts
  4. Registers can be negative, and the harmonic mean handles negative values
Show the answer

A. A single register with an unusually large maximum would dominate an arithmetic mean of 2Mj2^{M_j}; the harmonic mean damps such outliers

2Mj2^{M_j} has a heavy right tail: one register that happens to see a long run of zeros contributes an enormous term. Averaging 2−Mj2^{-M_j} and inverting bounds each register's influence, which is why HyperLogLog reaches LogLog's accuracy with about 64% of its memory (standard error 1.04/m1.04/\sqrt m against 1.30/m1.30/\sqrt m).

Further reading

  • G. Cormode & S. Muthukrishnan, "An improved data stream summary: the count-min sketch and its applications," Journal of Algorithms 55(1) (2005), 58–75.
  • N. Alon, Y. Matias & M. Szegedy, "The space complexity of approximating the frequency moments," Journal of Computer and System Sciences 58(1) (1999), 137–147 (STOC 1996).
  • P. Flajolet, É. Fusy, O. Gandouet & F. Meunier, "HyperLogLog: the analysis of a near-optimal cardinality estimation algorithm," Proceedings of the Conference on Analysis of Algorithms (AofA) (2007).
  • D. M. Kane, J. Nelson & D. P. Woodruff, "An optimal algorithm for the distinct elements problem," Proceedings of ACM PODS (2010), 41–52.
  • G. Cormode & K. Yi, Small Summaries for Big Data (Cambridge University Press, 2020).