Data Structures · Visualization
HyperLogLog: Add
HyperLogLog
Adding hashes the item, picks its register, and possibly raises that register's stored maximum — or changes nothing at all. Time: O(1) — hash plus one max. Space: O(1) extra.
Big-O: O(1) per item; ~12 KB for billions of distinct.
HyperLogLog: Add
HyperLogLogAdding hashes the item, picks its register, and possibly raises that register's stored maximum — or changes nothing at all. Re-adding a duplicate is automatically a no-op, which is exactly why distinct counting works: repeats can never inflate the estimate, only new faces can.
How Add Works
- h = hash(item); register = first p bits of h.
- zeroes = leading zeroes of the remaining bits (plus 1).
- registers[register] = max(registers[register], zeroes).
- Duplicates recompute the same zeroes → maximum unchanged.
Add Worked Example
Input: Add 'bob' twice to registers [3, 2, 0, 1]
- First 'bob': register 3, zeroes 1 → reg3 stays max(1, 1) = 1.
- Hmm — try 'dan': register 2, zeroes 4 → reg2 jumps 0 → 4.
- Second 'bob': identical hash → reg3 unchanged.
- New distinct faces move registers; repeats never do.
Output: Registers [3, 2, 4, 1] — only 'dan' moved the needle
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: addBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Add Time & Space Complexity
When to Use Add
- Deduplicated event ingestion (retries are harmless)
- Merging sketches from many servers by taking per-register max
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.