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

HyperLogLog

Adding 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

  1. h = hash(item); register = first p bits of h.
  2. zeroes = leading zeroes of the remaining bits (plus 1).
  3. registers[register] = max(registers[register], zeroes).
  4. Duplicates recompute the same zeroes → maximum unchanged.

Add Worked Example

Input: Add 'bob' twice to registers [3, 2, 0, 1]

  1. First 'bob': register 3, zeroes 1 → reg3 stays max(1, 1) = 1.
  2. Hmm — try 'dan': register 2, zeroes 4 → reg2 jumps 0 → 4.
  3. Second 'bob': identical hash → reg3 unchanged.
  4. New distinct faces move registers; repeats never do.

Output: Registers [3, 2, 4, 1] — only 'dan' moved the needle

Try your own input
HyperLogLog: Introduction
Distinct counting in KBs: longest zero-runs imply scale.
0
r0
0
r1
0
r2
0
r3
0
r4
0
r5
0
r6
0
r7
Updated register Max zero-run seen
HyperLogLog: Introduction
Press ▶ Run to watch it step by step.
Python · HyperLogLog in Code
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: add
Input: Add 'bob' twice to registers [3, 2, 0, 1]

Behind 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

TimeO(1) — hash plus one max
SpaceO(1) extra

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.