Sub topic 3
The key idea: rare bit patterns signal large sets
This chapter assumes you know basic Python, how integers are written in binary, what a hash function does at a conceptual level, and simple probability such as independent events. It also assumes the previous chapter's result: a good hash turns each item into a string of bits that behave like fair coin flips.
From coin flips to cardinality
Suppose you flip a fair coin until it lands heads. If the first heads comes on flip 1, that is unremarkable. If it takes 10 flips, you got 9 tails in a row, which happens about once in 512 tries. Seeing such a streak suggests you probably tried many times.
HyperLogLog applies this to hashes. A hashed item is a sequence of random bits. Reading from the left, we count how many bits it takes to reach the first 1-bit. That position is the item's rank.
1xxxx...has rank 1.01xxx...has rank 2.0001x...has rank 4.
Each bit is 0 or 1 with probability 1/2, independently. So the probabilities are:
| Rank k | Pattern prefix | P(rank = k) | P(rank ≥ k) |
|---|---|---|---|
| 1 | `1` | 1/2 | 1 |
| 2 | `01` | 1/4 | 1/2 |
| 3 | `001` | 1/8 | 1/4 |
| 10 | nine 0s, then `1` | 1/1024 | 1/512 |
| k | k−1 zeros, then `1` | 2^−k | 2^−(k−1) |
A rank of k shows up in about one of every 2^k items. So if the largest rank you have seen is k, you have probably looked at about 2^k distinct items.
Why duplicates do not matter
Hashing is deterministic. The same item always produces the same bits and the same rank. Seeing user-42 a million times gives the same rank every time, so it cannot change the maximum. Only distinct items can push the maximum up. That is why this trick counts distinct values and not total events.
The sketch also needs very little memory. It stores one small integer, the maximum rank so far, instead of the items. A rank for a 64-bit hash never exceeds 65, so it fits in one byte.
Trying it
This script computes the rank of each hashed item and tracks the maximum for streams of different sizes.
import hashlib
def hash64(item):
digest = hashlib.sha1(item.encode("utf-8")).digest()
return int.from_bytes(digest[:8], "big")
def rank(x, bits=64):
# Position of the first 1-bit, counted from the left.
# An all-zero value gets bits + 1.
return bits - x.bit_length() + 1
for n in (10, 1_000, 100_000):
max_rank = max(rank(hash64(f"item-{i}")) for i in range(n))
print(f"n={n:>7} max rank={max_rank:>2} estimate={2 ** max_rank}")
# Duplicates do not change the maximum.
once = max(rank(hash64(f"item-{i}")) for i in range(1_000))
repeated = max(rank(hash64(f"item-{i % 1_000}")) for i in range(50_000))
print(once == repeated) # TrueThe estimates will be in the right order of magnitude, and each is a power of two. The last line prints True because the 50,000 events contain only the same 1,000 distinct items.
Why one maximum is not enough
The maximum rank is a noisy signal. The chance that no item among n reaches rank k is about (1 − 2^−(k−1))^n. When n is close to 2^(k−1), that is about e^−1, or 37%. So even at the "right" size, you often miss that rank. Equally, one lucky item in a small set can reach a high rank early.
The estimate is also coarse. Because it is always a power of two, 5,000 and 8,000 distinct items can give the same answer. A single maximum can easily be off by a factor of two or more, and one extreme value drives the whole result.
Averaging many independent estimates reduces this noise. The next chapter splits the stream across many registers, each keeping its own maximum.
Exercise
A stream's largest observed rank is 20. Roughly how many distinct items does the single-maximum estimate suggest, and what happens to that estimate if the same stream is replayed twice?
Show answer
About 2^20, which is roughly one million distinct items. Replaying the stream adds only duplicates, which hash to the same bits and ranks, so the maximum and the estimate stay the same.
Exercise
What is the probability that a random 64-bit hash has rank at least 8, and about how many distinct items do you need before you expect to see one?
Show answer
Rank at least 8 means the first 7 bits are all 0, which has probability 2^−7 = 1/128. You would expect to see one after about 128 distinct items.