How many distinct visitors hit a site with a billion requests? A hash set of every id would eat gigabytes. HyperLogLog answers in a few kilobytes: hash each item, count the leading zeros of the hash, keep the longest run per bucket, and the harmonic mean of those runs estimates the count — to within about 1%.
O(1) memory per bucket · ~1% error · streaming cardinality
hash → bits
Each item becomes a uniformly random bit string. Same item, same bits.
leading zeros
A run of k zeros is rare — it hints you've seen ~2ᵏ distinct hashes.
buckets
The first bits pick a bucket; each keeps the longest zero-run it has seen.
harmonic mean
Combine buckets so one lucky run can't blow up the estimate.
hll.js — hash, count zeros, keep the max per bucket
Ready
Stream of items flows in. Press Step: each item is hashed to 24 random-looking bits — the last 3 bits pick a bucket, the leading zeros of the rest give a rank ρ, and the bucket keeps the largest ρ it has seen. Duplicates hash the same, so they change nothing.
0
items seen
0
true distinct
0
estimate
How it works
The trick rests on one fact about random bits: the probability a hash starts with exactly k zeros is 1/2^(k+1). So the longest run of leading zeros you've ever seen is a noisy estimate of log₂(distinct count). Raise 2 to that and you have a cardinality — noisy, but free of storing anything but the record.
1
Hash the item
Map each element to a fixed-width, uniformly random bit string. Identical items produce identical bits — that's why duplicates are automatically ignored.
2
Pick a bucket
Use the first p bits as a bucket index (here p = 3, so 8 buckets). Splitting into many buckets is what tames the variance of a single estimate.
3
Rank the rest
On the remaining bits, count the leading zeros and add one: ρ = leadingZeros + 1. Store register[bucket] = max(register[bucket], ρ) — only the record survives.
✓
Combine the buckets
Estimate ≈ α·m²/Σ 2^(−register[j]) — a harmonic mean over buckets, times a bias constant α. More buckets, tighter estimate: error ≈ 1.04/√m.
Memory (m=16384)
~12 KB
Typical error
~0.8%
Add / query
O(1)
Merge two
O(m)
The code
# m = 2^p buckets; register[] all start at 0def add(x):
h = hash(x) # uniform bits
idx = h & (m - 1) # first p bits pick a bucket
w = h >> p # the rest
rho = leading_zeros(w) + 1 # length of the zero-run + 1
register[idx] = max(register[idx], rho)
def estimate():
Z = sum(2.0 ** -register[j] for j in range(m))
return alpha(m) * m * m / Z # harmonic-mean cardinality
Two HyperLogLog sketches merge by taking the element-wise max of their registers — so you can count distinct items across shards or time windows and combine the results exactly, without ever comparing raw ids. That mergeability is why it's everywhere: Redis PFCOUNT, Presto/BigQuery approximate COUNT(DISTINCT), and analytics pipelines all lean on it.
Quick check
1. Why does seeing the same item twice not change the estimate?
Right — HyperLogLog stores no items. A repeat produces the same hash, lands in the same bucket with the same ρ, and max leaves the register alone. That's why it counts distinct items for free.
2. Why split hashes across many buckets instead of tracking one longest run?
Right — one lucky hash with a long zero-run would wildly overcount. Many buckets, combined by a harmonic mean (which resists high outliers), shrink the error as you add buckets: ≈1.04/√m.
FAQ
What does HyperLogLog do?
Estimates how many distinct items are in a stream using a few kilobytes — a hash set would need memory proportional to the count.
Why do leading zeros count things?
With random bits, a run of k leading zeros has probability 1/2^(k+1), so the longest run observed is roughly log₂ of the number of distinct hashes.
How accurate is it?
With m = 16384 buckets it uses ~12 KB and hits ~0.8% relative error. The small m = 8 here is for visibility — it's deliberately noisy.
Can two sketches be combined?
Yes — take the element-wise max of their registers. This mergeability lets you union counts across shards or windows exactly.
The picture: one hash, two jobs
Two of the page’s stream items run through its 24-bit hash. The last 3 bits pick one of 8 registers; the remaining 21 bits are scanned for leading zeros. The register keeps only the larger rank, so the whole stream ends as eight small numbers.
Worked example, step by step
Use the page’s own stream with p = 3 (8 registers) and its 24-bit FNV-style hash. The first 12 items are all distinct, and each row shows the first six bits of the 21-bit tail, because only the leading zeros matter. Registers start at 0.
Item
Bucket
Tail starts
ρ
Register
Effect
neuron
6
100101…
1
0 → 1
raise
octet
0
100010…
1
0 → 1
raise
scala
5
100101…
1
0 → 1
raise
proxy
3
101000…
1
0 → 1
raise
cache
5
010111…
2
1 → 2
raise
linux
5
101110…
1
2 → 2
keep
vector
2
100010…
1
0 → 1
raise
gadget
5
101010…
1
2 → 2
keep
kafka
1
001100…
3
0 → 3
raise
kotlin
4
100011…
1
0 → 1
raise
stream
5
011011…
2
2 → 2
keep
nibble
7
101000…
1
0 → 1
raise
Final registers: [1, 3, 1, 1, 1, 2, 1, 1]. The harmonic sum is 2⁻¹ six times, plus 2⁻³ and 2⁻², which is 3.375, so the estimate is α·m²/Z = 0.6356 × 64 / 3.375 = 12.05 against 12 true items. The two repeats at the end of the stream, cache and kafka, hash to the same bucket with the same rank and change nothing. Be careful with the tidy result: the standard error for 8 registers is about 1.04/√8 ≈ 37%, so landing this close is luck. Notice also that linux, gadget and stream landed in bucket 5, which cache had already raised to 2, so they left no trace at all. With thousands of items per bucket almost every item is discarded like this, which is why the sketch stays tiny.
Complexity and trade-offs
Case
Time
Space
Why
Hash set of every id
O(1) per add
O(n)
Exact, but memory grows with the number of distinct items.
Sort, then count unique
O(n log n)
O(n)
Exact and simple for a batch; no streaming.
Linear counting (bitmap)
O(1) per add
O(n) bits
Cheap, but the bitmap has to scale with the expected count.
HyperLogLog, m registers
O(1) per add
O(m)
Fixed memory whatever n is. Error is about 1.04/√m. A register needs 5 or 6 bits, so 4,096 of them pack into about 3 kB.
Merging two sketches
O(m)
O(m)
Element-wise max; exact for the union of the two streams.
Measured with the page’s Python hash on 100,000 distinct strings user-0…user-99999: 64 registers gave 108,724 (8.7% off, bound 13%), 1,024 gave 98,781 (1.2%, bound 3.3%), 4,096 gave 99,587 (0.4%, bound 1.6%) and 16,384 gave 98,679 (1.3%, bound 0.8%). The last one is a reminder that 1.04/√m is a standard deviation, not a ceiling: one run can land beyond it. You trade a small, tunable error for memory that never grows.
Common mistakes
A hash that is not uniform
Using the integer itself as its hash fails badly. Feeding 1 to 10,000 straight into 4,096 registers leaves a single register non-zero and the estimate comes out as 1.0, not 10,000. Always mix the bits first.
Using the same bits for bucket and rank
If the rank is counted over the whole hash, including the bits that chose the bucket, the two become correlated. With 4,096 registers and 100,000 items the estimate was 8,861. Shift the bucket bits off before counting zeros.
Rank without the +1
Storing the zero count itself makes an item with no leading zeros look like an empty register. On 50 distinct items and 4,096 registers the estimate was 28.1 instead of 50.3.
Merging by adding
Two streams that overlap, u0…u5999 and u3000…u8999, have 9,000 distinct items between them. Taking the register-wise max estimates 9,110. Adding the two estimates gives 12,058, because the shared 3,000 are counted twice.
Trusting the raw formula at small counts
With 4,096 registers and 12 items the raw harmonic formula says 2,959, because empty registers dominate. The linear-counting fallback, m·ln(m/empty), gives 12.0.
Where this shows up
Unique visitors and active users
Counting distinct users per page, per day or per campaign needs one sketch per key. Sketches are tiny, so you can keep millions of them and merge hourly ones into daily and weekly counts without the raw ids.
Database engines
Approximate distinct-count functions in analytic databases, and the planner statistics that estimate how many distinct values a column holds, use this family of sketches so a query does not need a full sort or hash.
Network and security telemetry
Counting distinct source addresses hitting a service is a standard scan or attack signal, and a sketch does it per destination at line rate.
Sharded and streaming pipelines
Because the merge is an element-wise max, each shard can sketch locally and a coordinator can combine them in any order, which is the property exact distinct counting lacks.
SOLVE IT YOURSELF
Solve it: count a billion distinct things in 4 KB
A hash set of a billion IDs needs gigabytes. HyperLogLog needs a few thousand small counters — and answers within about 2%. It works by noticing that a rare pattern implies a large sample. Python or TypeScript.
YOUR TASK
Implement build(items, b) — 2ᵇ registers, each holding the longest run of leading zeros seen — and estimate(regs), the harmonic-mean cardinality estimate with the small-range correction.
HINTS — 6 IDEAS
The core intuition: in random hashes, a value starting with k zeros shows up about once every 2ᵏ values. So seeing 10 leading zeros suggests you have seen roughly 2¹⁰ distinct things.
One estimate like that is wildly noisy, so split into 2ᵇ registers: the first b bits pick the register, the rest supply the zero-run.
Each register keeps only the maximum run it has seen. That is why the sketch is idempotent — feeding the same item twice changes nothing, which is exactly what counting distinct requires.
Combine with a harmonic mean, not an arithmetic one — it suppresses the single lucky register that would otherwise dominate. Then multiply by the bias constant α and by m².
At low cardinality most registers are still empty and the formula reads badly high, so switch to linear counting: m · ln(m / empty_count).
Accuracy is about 1.04/√m — 4096 registers gives roughly 1.6%, in a few kilobytes, no matter how many items you feed it.