Data Structures · Visualization

HyperLogLog: Estimate

HyperLogLog

The estimate blends every register with a harmonic mean, which tames registers that got lucky with one huge zero-run. Time: O(m) per estimate — one pass over registers. Space: O(1) extra.

Big-O: O(1) per item; ~12 KB for billions of distinct.

HyperLogLog: Estimate

HyperLogLog

The estimate blends every register with a harmonic mean, which tames registers that got lucky with one huge zero-run. Small ranges get a linear-counting correction; the standard error is about 1.04/√m (2% at m=4096). More registers cost a little memory and buy a lot of accuracy.

How Estimate Works

  1. Take the harmonic mean of 2^(−register) across all registers.
  2. Scale by the constant for m registers.
  3. If the raw estimate is small, switch to linear counting of empty registers.
  4. Report with ±1.04/√m error — and merge sketches with max when needed.

Estimate Worked Example

Input: Registers [3, 2, 4, 1] over m = 4

  1. Powers: 2^-3, 2^-2, 2^-4, 2^-1 → sum ≈ 0.77.
  2. Harmonic mean scaled by m²/sum → ≈ 5.2.
  3. Small-range correction pulls it toward ~4.
  4. Truth 4 distinct faces — within the expected error band.

Output: Estimate ≈ 4–5 distinct (standard error ±52% at m = 4 toy size)

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 estimate(regs):
    m = len(regs)
    raw = ALPHA * m * m / sum(2.0 ** -r for r in regs)
    if raw <= 2.5 * m:  # small-range fix
        zeros = regs.count(0)
        if zeros: raw = m * math.log(m / zeros)
    return raw  # ±1.04/sqrt(m)
# example: estimate
Input: Registers [3, 2, 4, 1] over m = 4

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.

Estimate Time & Space Complexity

TimeO(m) per estimate — one pass over registers
SpaceO(1) extra

When to Use Estimate

  • Sizing audiences and cardinality alarms on streams
  • Merging daily sketches into weekly uniques without reprocessing

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.