Counting Names Without Keeping the Guest List
A venue may record ten ticket scans but only six different visitors. If someone scans the same ticket repeatedly, the event count grows while the number of distinct ticket IDs does not. An exact distinct count would keep a set of every ID. A cardinality sketch instead keeps a compact trace of hashed IDs and estimates how many different IDs could have produced it. This target is often called $F_0$, the number of nonzero coordinates in an insert-only frequency vector.
Start with scans A, B, A, C, B, D. There are six scans and four distinct IDs: $\{A,B,C,D\}$. Imagine assigning each distinct ID a reproducible random rank in $(0,1)$, such as A: $0.12$, B: $0.68$, C: $0.42$, D: $0.31$. Repeated A has the same rank, so it cannot change the minimum. A small minimum suggests that many different IDs had chances to produce a rare low rank; it is evidence, not an exact conversion to four. Another approach notices unusually long runs of zero bits in hashes. Both approaches turn rare hash patterns into evidence about a set's size.
The key is the identity contract. Counting unique users, devices, or transactions requires stable canonical IDs for the intended entity. Repeated events should hash to the same value, and different workers must agree on encoding and hash seed to merge summaries. The previous chapters' hash assumptions and concentration tools tell us why one register is noisy, why aggregation helps, and where the guarantee ends.
Distinct counting estimates how many different keys appeared, not how many events arrived. Repeated appearances of an unchanged key leave a correctly updated insert-only cardinality sketch unchanged; an estimate still needs a stated error model and hash assumptions.
| Concept | Intuitive meaning and exact example | Non-example or assumption | Question answered |
|---|---|---|---|
| Event count | Six scans in A, B, A, C, B, D | This is not the number of unique visitors | How many records arrived? |
| Distinct count $F_0$ | Four observed IDs: A, B, C, D | One person with two IDs may count twice | How many different keys arrived? |
| Stable hash | Both occurrences of A receive the same rank | Fresh random rank per event destroys duplicate invariance | How are repeats recognized implicitly? |
| Minimum rank | Smallest of $0.12,0.68,0.42,0.31$ is $0.12$ | One observed minimum is noisy | What rare value did the keys produce? |
| Register | Store a maximum leading-zero statistic for one hash partition | A register does not store the guest list | What evidence can be kept cheaply? |
| Union | $\{A,B,C\}\cup\{B,D\}=\{A,B,C,D\}$ | Adding local distinct counts gives five, not four | How many keys appear across groups? |
Counting Names Without Keeping the Guest List
Use scans A, B, A, C, B, D and fixed ranks A: $0.12$, B: $0.68$, C: $0.42$, D: $0.31$. Checkpoint 1: after the first four scans, the distinct set is $\{A,B,C\}$ and the minimum rank is $0.12$. Checkpoint 2: after all six, the distinct set is $\{A,B,C,D\}$, yet the minimum remains $0.12$; one extra distinct ID need not alter a sketch. Sort the four distinct ranks and find the third smallest, $0.42$. Reflection: why must both appearances of A share one rank, and why can no single observed statistic reveal the exact distinct count in general?
From Occupancy to Leading-Zero Statistics
Fix a set $S$ of $n$ distinct keys and a stable hash function. In a mathematical idealization, each distinct key receives an independent uniform hash value; repeats reuse that value. For a uniform binary hash, the probability that a value ends in at least $r$ zero bits is $2^{-r}$, as long as the hash has enough bits. Among about $n$ distinct values, seeing a run near $\log_2n$ is plausible. The Flajolet–Martin idea records the largest trailing-zero run or related bitmap evidence. Turning that statistic into an estimate requires calibration and variance control; $2^R$ alone is not an unbiased general estimator. Leading-zero conventions express the same rarity when bit order is chosen consistently.
Another view uses hash order statistics. Give each distinct key an independent continuous uniform rank in $(0,1)$ and sort the ranks. For $1\le k\le n$, the $k$th smallest rank $R_k$ has $\mathbb E[R_k]=k/(n+1)$. For $k>1$, $\mathbb E[1/R_k]=n/(k-1)$, so $(k-1)/R_k$ is unbiased for $n$ under this ideal model. One sample can still be far from $n$, and the reciprocal of the single minimum has infinite mean in this continuous idealization. Real finite-width hashes also have ties and a limited range; the ideal equations are not automatically exact for a deployed implementation.
Stochastic averaging splits keys among several registers using hash-prefix bits, reducing reliance on a single extreme run. LogLog-type schemes aggregate register values with calibrated constants; HyperLogLog (HLL) uses a harmonic-style aggregation of powers of the register values. If $m$ is a power of two, the first $\log_2m$ hash bits select register $j$, and the suffix contributes $\rho$, the position of its first $1$ bit, starting at $1$. Update $M_j\leftarrow\max(M_j,\rho)$. A common raw estimate has form $E_{\mathrm{raw}}=\alpha_m m^2/(\sum_{j=1}^{m}2^{-M_j})$, with a calibration factor $\alpha_m$. Practical implementations need corrections, especially when cardinality is small relative to $m$ or approaches the finite hash range.
At small cardinalities, linear counting uses the number $V$ of empty registers or buckets: $\widehat n\approx m\ln(m/V)$ when $V>0$, under a suitable uniform occupancy model. The familiar HLL small-range correction uses this idea when many registers are still zero; the exact switch and bias correction belong to an implementation's documented estimator. When $V=0$, the formula cannot be used. None of these insert-only summaries directly supports removing an arbitrary key that may still occur elsewhere.
flowchart TD
S["Stable hash per distinct key"] --> R{"Retained statistic"}
R -->|Small ranks| O["Order statistics"]
R -->|Rare zero runs| F["Flajolet-Martin idea"]
F --> A["Partition into registers"]
A --> L["LogLog or HLL aggregation"]
A --> V["Empty-register occupancy"]
V --> C["Linear-counting correction"]
O --> E["Estimated F0"]
L --> E
C --> E
classDef navy fill:#17365D,color:#fff,stroke:#17365D;
classDef teal fill:#147D84,color:#fff,stroke:#147D84;
classDef crimson fill:#C6284D,color:#fff,stroke:#C6284D;
classDef purple fill:#6C3BAA,color:#fff,stroke:#6C3BAA;
class S,R navy; class O,F,A,L,E teal; class V,C purple;
| Statistic or method | Exact ideal-model statement | Assumption | Boundary or consequence |
|---|---|---|---|
| Trailing zeros | $\Pr(\text{at least }r\text{ zeros})=2^{-r}$ | Uniform independent binary hash bits | Finite hash width limits maximum run |
| Minimum rank | $\Pr(R_1>u)=(1-u)^n$ for $0\le u\le1$ | Independent continuous uniform ranks for distinct keys | One minimum is noisy; repeats must keep rank |
| $k$th order statistic | $\mathbb E[R_k]=k/(n+1)$ | $1\le k\le n$ in continuous idealization | Mean inversion is not itself an unbiased inverse |
| Reciprocal statistic | $\mathbb E[(k-1)/R_k]=n$ for $k>1$ | Independent continuous ranks, no ties | $k=1$ has divergent reciprocal mean |
| HLL register | $M_j$ is maximum suffix $\rho$ for keys routed to $j$ | Consistent hash split, enough bits | Repeats do not change the maximum |
| Linear occupancy | $m\ln(m/V)$ when $V>0$ | Suitable uniform bucket model and small-range use | Undefined at $V=0$ |
The register update is an invariant, not a cardinality formula: each $M_j$ is the largest leading-zero-derived value ever seen among keys routed to $j$. Estimating $F_0$ from those maxima requires a calibrated aggregation and a model for the hash outputs; one exceptional hash can make a single-register estimate very noisy.
Bias, Variance and Register Aggregation
Rare patterns provide a scale but not a ready-made accuracy guarantee. For uniform independent hashes, $\Pr(R_1>u)=(1-u)^n$: all $n$ ranks must exceed $u$. A very small observed minimum is possible even for a small set. Using $1/R_1$ as if it were a reliable count fails sharply: for continuous ranks its expected value diverges. Keeping the $k$th smallest rank with $k>1$ avoids that particular pathology. The estimator $(k-1)/R_k$ is unbiased for $n$ under the ideal model, yet its variance is finite only when $k>2$; for $k>2$, $\operatorname{Var}((k-1)/R_k)=n(n-k+1)/(k-2)$. This follows from the beta distribution of $R_k$ and its reciprocal moments, not from merely replacing a random denominator by its mean.
For HLL, multiple registers spread keys across partitions and the harmonic-style denominator dampens the influence of one unusually large register. Under an appropriate ideal hash model and sufficiently large cardinality, the familiar asymptotic relative standard error is about $1.04/\sqrt m$ for the classical estimator; this is a rule of thumb for its operating regime, not a universal guarantee at tiny $n$, hash saturation, or adversarial inputs. An estimate also has bias, especially at range boundaries; empirical corrections and an empty-register regime matter. A confidence statement needs an actual error analysis or measured calibration, not only an RSE number.
Union estimation has a clean state rule. If sketches A and B share the same hash function, register count, encoding, and register definitions, then for each $j$, $M_j(A\cup B)=\max(M_j(A),M_j(B))$. Proof: the maximum over all keys in a union is the maximum of the two local maxima. Duplicate keys yield identical hash outcomes and do not add new evidence. The cardinality estimate is computed after the coordinatewise merge; adding the two scalar estimates double-counts overlap and is not the HLL union operation. The same maximum cannot undo a deletion or remove one day from a combined sketch, since it does not record which contributing key supplied a maximum.
flowchart TD
H["Stable uniform hash per key"] --> R["Rare rank or zero-run observation"]
R --> S{"How much state?"}
S -->|One minimum| V["High or infinite reciprocal variance"]
S -->|kth smallest, k > 2| O["Unbiased inverse-rank estimate"]
S -->|Many registers| M["HLL calibrated aggregation"]
M --> U["Compatible union: max per register"]
O --> E["Analyze bias, variance, and range"]
M --> E
U --> E
V --> E
classDef navy fill:#17365D,color:#fff,stroke:#17365D;
classDef teal fill:#147D84,color:#fff,stroke:#147D84;
classDef crimson fill:#C6284D,color:#fff,stroke:#C6284D;
classDef purple fill:#6C3BAA,color:#fff,stroke:#6C3BAA;
class H,R navy; class O,M,U,E teal; class V crimson; class S purple;
Bias, Variance and Register Aggregation
Given: compatible four-register states A: $(3,1,0,2)$ and B: $(1,4,2,1)$. Merge them coordinatewise to obtain $(3,4,2,2)$. Checkpoint: A's second register changes from $1$ to $4$ because B supplies a larger observation; A's first stays $3$. Compute the raw HLL denominator for the merged toy state: $2^{-3}+2^{-4}+2^{-2}+2^{-2}=11/16=0.6875$. A raw formula would then be $\alpha_4\,4^2/(11/16)$, but this four-register illustration is too small to treat as a calibrated production estimate. Variation: give B a different hash seed. Coordinate 2 no longer represents the same partition, so taking maxima has no justified union meaning. Reflection: why can neither max-merge nor the final scalar estimate reveal which region supplied a duplicate key?
| Analytical viewpoint | Establishes | Assumptions and limits | Failure case |
|---|---|---|---|
| Single minimum | $\Pr(R_1>u)=(1-u)^n$ | Independent continuous ranks; weak one-sample evidence | Reciprocal of minimum has infinite mean |
| $k$th rank | Unbiased $(k-1)/R_k$ for $k>1$ | Ideal uniform ranks; finite variance only for $k>2$ | Replacing random $R_k$ with its expectation |
| Several HLL registers | Relative error scales roughly as $1/\sqrt m$ in an ideal regime | Bias correction, hash quality, finite-range effects | Quoting $1.04/\sqrt m$ as a universal tail guarantee |
| Empty-register correction | $m\ln(m/V)$ for $V>0$ | Appropriate small-range occupancy model | All registers occupied, $V=0$ |
| Coordinatewise max | Exact register state for union of compatible sketches | Same hash, register layout, encoding, and precision | Different seeds or layouts make arrays incomparable |
| Scalar estimate addition | Generally invalid for union | Requires exact disjointness and separately justified combination | Shared users counted twice |
Daily Users, Devices and Distributed Unions
Approachable daily visitors. A small museum records IDs on Monday A, B, C, A and Tuesday B, D, E. Monday has three distinct IDs, Tuesday has three, and their union has five, not six. Counting individual scans would give seven. A shared-hash cardinality sketch can merge compatible daily states by register maxima to estimate the union; it cannot subtract Monday's contribution later to recover Tuesday unless Tuesday's own sketch was retained.
Production analytics. Consider daily active user estimates from four regions, each processing millions of events. The specification must define the user ID, what “day” means in each region, how late events are assigned, and whether opt-outs or deleted accounts are excluded. All workers need identical hash version, seed, register count, and encoding. Their register arrays can be merged for a global daily union. If the target requires a 2% relative standard error in the classical large-range approximation, $m$ around $(1.04/0.02)^2=2{,}704$ suggests choosing a supported power of two such as $4{,}096$ registers. The actual memory includes register width and metadata; a confidence or service-level promise needs testing across realistic cardinalities, including small groups and hash-range boundaries.
Misleading or adversarial case. Device IDs rotate for privacy, causing one physical device to look like several distinct keys. Conversely, two people sharing one account ID look like one user. Neither is “fixed” by increasing registers. If an adversary can choose identifiers after learning the hash seed, it may seek values that distort register patterns; fixed-key random-hash analyses do not cover that choice. Small groups can also yield unstable estimates or privacy concerns, so an exact threshold decision may require an authoritative count or a separate policy. These are target-definition and threat-model questions before they are estimator questions.
Daily Users, Devices and Distributed Unions: Distinct Elements & Set Cardinality
Inputs: Monday events A, B, C, A; Tuesday events B, D, E. Model selection: use distinct IDs per day and a union over both days; do not sum event counts or daily distinct counts. Hand calculation: Monday set $\{A,B,C\}$ has size 3, Tuesday $\{B,D,E\}$ has size 3, and the union $\{A,B,C,D,E\}$ has size 5. The intersection $\{B\}$ explains $3+3-1=5$. Expected observation: a shared-hash register union should represent these five stable keys, though a tiny sketch need not output exactly 5. Success criterion: write all three sets, distinguish seven events from five distinct IDs, and state the configuration requirement for register merging. Changed assumption: if B's ID rotates between days, explain how the target changes.
Daily Users, Devices and Distributed Unions: Distinct Elements & Set Cardinality
Workload: four regions, millions of daily events, global daily active users, target around 2% relative standard error in the HLL large-range regime. Decision worksheet: (1) Define a canonical user ID, timezone and event-time window, duplicate and late-event policies. (2) Record common hash seed and version, precision, register serialization, and merge compatibility checks. (3) Start evaluation at $m=4{,}096$ registers, giving idealized RSE about $1.04/64\approx1.625\%$ before range and system effects; size actual memory from register width and metadata. (4) Compare sketches with exact counts on sampled days and cardinality scales; measure bias, error quantiles, late-arrival correction, and hash quality. (5) Retain daily sketches if old days must be removed from a reporting window; a combined max state cannot be subtracted. Acceptance: written error and operational budgets, merge tests across regions, small-range checks, and a fallback for exact threshold decisions.
Plan a Cardinality Study
Pick the entity and time scope before the sketch. Then decide which ideal hash model the estimator's reasoning uses, how much state is available, and whether the answer must be mergeable, retractable, or exact near a decision threshold. The exercises make the distinction between mathematical sketch error and inconsistent IDs visible.
Practice: Plan a Cardinality Study
Level 1 — Define (2 points). For events A, B, A, C, B, D, give the event count and $F_0$. Expected: 6 and 4. Explain which value an exact frequency-vector zero norm counts and why repeats do not change it.
Level 2 — Rare patterns (2 points). For a sufficiently long ideal binary hash, calculate the chance of at least four trailing zeros. Expected: $1/16$ for one distinct key. Hint: each required trailing bit is zero with probability $1/2$. Explain why observing one such key is not proof of exactly 16 distinct keys.
Level 3 — Order statistic (2 points). Given distinct ranks $0.12,0.31,0.42,0.68$, use $k=3$ to compute $(k-1)/R_k=2/0.42\approx4.76$. Expected: a noisy estimate, not the known exact count 4. State the independent continuous-rank assumption and why the $k=1$ reciprocal lacks finite mean in that ideal model.
Level 4 — Merge (2 points). Combine compatible arrays $(3,1,0,2)$ and $(1,4,2,1)$. Expected: $(3,4,2,2)$. State why adding arrays, adding final estimates, or max-merging arrays generated with different seeds fails. Edge case: explain why deleting the key that set the maximum cannot be handled by a simple decrement.
Level 5 — Professional study (2 points). Draft a daily-user plan across regions: identity encoding, time window, expected range, precision, hash seed, merge protocol, error metric, validation against exact counts, and a process for late events or deletions. Artifacts: one-page contract, a tiny exact-set trace, and a table of expected versus measured error across low and high cardinality. Rubric: identity/time model 2, mathematical derivation 2, merge correctness 2, bias/range evaluation 2, failure and fallback plan 2. Stretch: compare register-based estimation with a $k$th-minimum sketch under the same memory budget and discuss when an exact set is preferable.
Before reporting $F_0$, verify the identity unit, stable hash configuration, cardinality range, small-range correction, register precision, and union semantics; measure error against exact counts where possible. This connects the previous chapter's sampling and hash reasoning to the upcoming frequency-estimation methods, which ask how often each key appears rather than how many different keys exist.
Next in the Series
In Frequency Estimation & Point Queries, we'll explore Answer point queries with compact hashed counters..