Data Structures · Visualization
HyperLogLog: Introduction
HyperLogLog
HyperLogLog counts DISTINCT items — how many different users visited — in about 12 KB no matter the scale. Time: O(1) per item — one hash. Space: O(m) small registers (~12 KB standard).
Big-O: O(1) per item; ~12 KB for billions of distinct.
HyperLogLog: Introduction
HyperLogLogHyperLogLog counts DISTINCT items — how many different users visited — in about 12 KB no matter the scale. It hashes each item, uses the first bits to pick one of m registers, and stores the longest run of leading zeroes seen there. Rare long zero-runs imply many distinct items: twice as many items make the longest run one bit longer on average.
How HyperLogLog: Introduction Works
- Hash every item to a fixed bit-string.
- First p bits choose a register (m = 2^p of them).
- Count leading zeroes in the rest; keep the maximum per register.
- Combine all registers with a harmonic mean → distinct estimate.
HyperLogLog: Introduction Worked Example
Input: 4 registers; observe 'amy', 'bob', 'amy', 'cid'
- 'amy' → register 1, zeroes 2 → reg1 = 2.
- 'bob' → register 3, zeroes 1 → reg3 = 1.
- 'amy' again → same register, same zeroes → no change (duplicates free!).
- 'cid' → register 0, zeroes 3 → reg0 = 3.
Output: Registers [3, 2, 0, 1] → estimate ≈ 4 distinct (truth 3)
Press ▶ Run to watch it step by step.
def add(regs, x, p=14):
h = hash64(x)
r = h >> (64 - p) # register index
z = leading_zeroes(h) + 1
regs[r] = max(regs[r], z) # duplicates: no-op
# O(1): one hash
# example: introHyperLogLog: Introduction Time & Space Complexity
When to Use HyperLogLog: Introduction
- Daily active users and unique visitors at web scale
- Redis PFADD / BigQuery APPROX_COUNT_DISTINCT under the hood
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.