Universal Hashing & Sketches
Random hash functions with guarantees, and the data summaries built from them.
Every hash function you can write down has a worst input: a set of keys that all land in one slot. An attacker who knows your function can find that set and turn your table into a linked list. The cure is to let the table pick its function at random, and the same trick powers Bloom filters and sketches, which answer questions about data they never store.
What you’ll learn
- Explain why every fixed hash function has inputs that make a table quadratic, and define a universal family.
- Prove that is universal and that it gives an expected chain length of at most on every input.
- Derive a Bloom filter's false-positive rate, its best number of hash functions and its cost of about bits per element.
- State what Count-Min and HyperLogLog estimate, with what error and how much memory.
- Recognize when a problem calls for randomized hashing, a Bloom filter or a sketch.
Every fixed hash function has a bad input
A hash table promises lookups, but the promise depends on the keys. Fix any hash function from a universe of possible keys to slots. If , the pigeonhole principle puts at least keys of into one slot, and whoever knows can insert exactly those keys.
With chaining they all join one chain. The -th insertion scans the keys already there to rule out a duplicate, so insertions cost key comparisons. For that is about comparisons where you expected about .
Universal families
No collisions modulo . Fix keys and let and . Then . Neither nor is divisible by , and is prime, so their product is not either:
The pair is uniformly random. Since has an inverse modulo , each pair comes from exactly one . So is a bijection from the functions onto the ordered pairs of distinct residues:
Count the bad pairs. Now exactly when . For a fixed , the values in with number at most
Conclude. Given , all values of are equally likely, and at most of them cause a collision:
import random
P = (1 << 61) - 1 # a Mersenne prime, larger than any key
class UniversalHash:
"""h(x) = ((a*x + b) mod P) mod m, with a and b drawn once, at random."""
def __init__(self, m):
self.m = m
self.a = random.randrange(1, P)
self.b = random.randrange(0, P)
def __call__(self, x): # x: an integer key, 0 <= x < P
return ((self.a * x + self.b) % P) % self.mDraw and once per table, never once per call: the guarantee is about one function applied to all keys. Python's integers compute the 122-bit products exactly; in C++, use a 128-bit product or reduce with . Keys must be integers below , so map strings to integers first, for example with the polynomial hash of the String Matching lesson.
What universality buys, and what it does not
Universality is a statement about pairs of keys, and pairs are all a chained hash table needs. Fix any set of keys first, then draw .
For a key , let if and otherwise. The chain that hashes to holds itself (if ) and every other key with :
Universality gives . Linearity of expectation needs no independence between the :
So an unsuccessful search scans at most keys in expectation and a successful one at most , where is the load factor. Keep by doubling the table (with a freshly drawn ) and every operation costs expected time, amortized over the resizes:
Two pieces of fine print. First, the bound is an expectation over : an unlucky draw can still make one chain long, but no input can force it. Second, the input must not depend on . An attacker who can probe the table, for instance by timing lookups, may learn about and then choose colliding keys after all.
A server stores user-supplied keys in a chained hash table. It draws from a universal family once, at startup, and never redraws it. An attacker sends keys, measures how long each request takes, and adapts its next keys. Which statement is right?
- Each operation still takes expected time, because universality holds for every input
- The guarantee no longer applies: keys chosen after observing 's behavior can pile into one slot
- The attacker learns nothing, because was drawn at random
- Universality caps every slot at two keys, so the damage is bounded
Show the answer
B. The guarantee no longer applies: keys chosen after observing 's behavior can pile into one slot
The proof fixes the keys first and then draws , so every key must be independent of . Timing leaks information about , and an adaptive attacker can steer later keys toward a slot it has learned to hit. Defenses are a keyed cryptographic hash such as SipHash with a secret key, redrawing when chains grow too long, or both (see the Optimal lesson Hash Flooding & Anti-Hash Tests).
| Family | Guarantee | Cost | |
|---|---|---|---|
| Carter–Wegman | universal | a multiplication and a reduction mod | |
| Multiply-shift (Dietzfelbinger et al., 1997) | , odd, | one multiplication and one shift | |
| Polynomial of degree | -independent | multiplications | |
| Simple tabulation (Zobrist, 1970) | XOR of random table entries, one per byte of | 3-independent, yet behaves like a random function for linear probing | one table lookup per byte |
| SipHash (Aumasson & Bernstein, 2012) | a keyed pseudorandom function | collisions are hard to find without the secret key (a cryptographic assumption, not a theorem) | slower; used for strings by CPython and by default in Rust's HashMap |
Bloom filters: membership in a few bits per key
Sometimes even a hash table is too big. A web crawler that has seen URLs of about 80 bytes each would need some 800 gigabytes to remember them exactly. If an occasional wrong "seen it" is acceptable (the crawler skips one page it never fetched), a Bloom filter does the job in about 12 gigabytes.
A Bloom filter (Bloom, 1970) is an array of bits, all 0 at first, with hash functions. To insert , set the bits to 1. To query , look at those bits. If any of them is 0, then was never inserted, for certain. If all are 1, then is probably present: other keys may have set those bits, which is a false positive.
import hashlib, math
class BloomFilter:
def __init__(self, n, eps): # capacity n, false-positive rate eps
self.m = math.ceil(n * math.log(1 / eps) / math.log(2) ** 2)
self.k = max(1, round(self.m / n * math.log(2)))
self.bits = bytearray((self.m + 7) // 8)
def _positions(self, item):
d = hashlib.blake2b(item.encode(), digest_size=16).digest()
h1 = int.from_bytes(d[:8], 'little')
h2 = int.from_bytes(d[8:], 'little') | 1
return [(h1 + i * h2) % self.m for i in range(self.k)]
def add(self, item):
for p in self._positions(item):
self.bits[p >> 3] |= 1 << (p & 7)
def __contains__(self, item):
return all(self.bits[p >> 3] >> (p & 7) & 1 for p in self._positions(item))For and this allocates bits and functions. Two hash values give all positions as (Kirsch & Mitzenmacher, 2006) with the same asymptotic false-positive rate as independent functions. Use a stable hash such as hashlib: Python's built-in hash() of a string changes from one run to the next.
Model each as uniform and independent. After insertions, a given bit has escaped all bit settings with probability
A key that was never inserted is reported present when all of its bits are 1. Treating those bits as independent, a slight approximation that the Optimal lesson makes exact:
More functions test more bits but also fill the array faster. Substitute : the exponent is symmetric under and smallest at , when half the bits are set:
Solve for the space. Each element costs, whatever it is (a URL, an IP address, a DNA fragment),
How many bits per element does a Bloom filter need for a 1% false-positive rate, using the best number of hash functions?
Show the answer
9.6 bits
bits, with , so 7 hash functions. Every halving of the error rate costs another 1.44 bits per element, independent of how large the elements are.
| False-positive rate | Bits per element | Best (rounded) |
|---|---|---|
| 10% | 4.8 | 3 |
| 1% | 9.6 | 7 |
| 0.1% | 14.4 | 10 |
| 0.01% | 19.2 | 13 |
Sketches: summaries of a stream you cannot store
A streaming algorithm reads a data stream once, in order, with memory far smaller than the stream. The small summary it keeps is a sketch. Two sketches built on random hash functions answer the most common questions: how often did an item occur, and how many distinct items were there?
Every counter that touches holds plus whatever collided with in that row, so : a Count-Min sketch never underestimates. With columns and rows, the overestimate exceeds , where is the length of the stream, with probability at most . For and that is counters, whether the stream holds a thousand distinct items or a billion.
To count distinct items, hash each one to a random-looking bit string. Among distinct hashes, the longest run of leading zeros is about , because a given hash starts with zeros with probability . A single maximum is a noisy estimate, so HyperLogLog (Flajolet, Fusy, Gandouet & Meunier, 2007) splits the hashes among registers, keeps the maximum in each and combines them with a harmonic mean. Its standard error is about : registers of 6 bits, 12 KB in all, give about 0.8%, and duplicates never change a register.
| Question | Exact answer | Sketch | Memory of the sketch |
|---|---|---|---|
| Is in the set? | hash set: every element stored | Bloom filter: false positives at rate | bits per element |
| How often did occur? | hash map: one counter per distinct item | Count-Min: overestimate with probability | counters |
| How many distinct items? | hash set: every distinct item stored | HyperLogLog: standard error | registers of 5–6 bits |
Recognizing it
Reach for these tools when a problem statement shows one of three signals:
- The keys are chosen by someone else, possibly an opponent (user input on a server, hacking tests in a contest), and worst-case behavior matters: draw the hash function at random, or use a keyed hash with a secret seed.
- The set is too large to store, and a rare false "yes" can be tolerated or double-checked: a Bloom filter.
- The data is a stream you cannot keep, or it is spread across machines, and approximate counts are enough: a sketch, Count-Min for frequencies and HyperLogLog for distinct counts.
| Problem | Key idea | Cost |
|---|---|---|
| A crawler must never fetch a URL twice, across billions of URLs | A Bloom filter of visited URLs; a false positive only skips one page | about 9.6 bits per URL at 1%, bit probes per query |
| Distinct visitors per page per day, logged by many servers | One HyperLogLog per page and server, merged by register maxima | 12 KB per counter for about 0.8% error |
| The most frequent search queries in an endless stream | Count-Min estimates plus a min-heap of the current top (or the deterministic Misra–Gries summary) | counters, per item |
| A web server builds hash tables from request parameters | A keyed hash with a secret random seed, so no one can aim at a slot | expected per operation |
| Counting equal pairs among integers in a contest where others may submit hacking tests | A hash map with a randomized hash function, drawn at run time | expected |
Common bugs:
- Drawing a new random function per call, or per restart for data saved to disk. The function is fixed for the structure's lifetime, and a saved filter must store its seed.
- Using Python's
hash()on strings in a persistent filter: it is randomized per process, so a reloaded filter answers wrongly. - Keys that are not below , or a modulus that is not prime: universality is silently lost.
- Sizing a Bloom filter for elements, then inserting : the false-positive rate jumps from 1% to about 16%.
- Feeding a Count-Min sketch negative updates: its minimum can then underestimate, so streams with deletions call for a median-based estimator.
- A 32-bit hash in HyperLogLog: it saturates near distinct items. Use 64-bit hashes.
Every minute, each of 200 routers must report how many distinct source IP addresses it saw, and a dashboard must show the distinct count for the whole network, using a few kilobytes per router. Which structure fits?
- A hash set of addresses per router, merged at the dashboard
- A Count-Min sketch per router, adding up its counters
- A HyperLogLog per router, merged by register maxima
- A Bloom filter per router, queried by the dashboard for every possible address
Show the answer
C. A HyperLogLog per router, merged by register maxima
HyperLogLog estimates distinct counts in a few kilobytes, and the register-wise maximum of 200 sketches is exactly the sketch of the combined stream, so addresses seen by several routers are not double-counted.
Key takeaways
- No fixed hash function is good for every input. Drawing from a universal family, with , makes the expected chain length at most for every input fixed independently of .
- with a prime is universal; multiply-shift is the fast practical choice, with collision probability at most . Adaptive attackers who learn break the guarantee, so servers use keyed hashes such as SipHash.
- A Bloom filter with hash functions has a false-positive rate of about : roughly bits per element, no false negatives and no deletions.
- Sketches trade exactness for memory: Count-Min overestimates a frequency by at most with probability , and HyperLogLog counts distinct items with standard error about . Both merge across machines.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A table stores keys chosen by an adversary who knows your code but not your random bits. You draw from a universal family when the table is created. What is guaranteed?
- No two keys ever collide
- Every lookup takes time in the worst case
- For every set of keys fixed in advance, each lookup takes expected time
- Lookups take time on average, provided the keys are random
Show the answer
C. For every set of keys fixed in advance, each lookup takes expected time
Universality bounds each pair's collision probability by , so the expected chain length is at most for any key set chosen independently of . The expectation is over , not over the keys.
Where does the proof that is universal use that is prime?
- To make divide
- To make the final reduction mod uniform
- Nowhere: any modulus larger than the keys works
- To show that and that has an inverse modulo
Show the answer
D. To show that and that has an inverse modulo
Modulo a prime there are no zero divisors, so and give , and is invertible, which makes a bijection. With , and , the keys would collide modulo already.
A Bloom filter was sized for elements at a 1% false-positive rate (about bits, ). By mistake, elements are inserted. About what is its false-positive rate now?
- 2%
- 4%
- 16%
- 50%
Show the answer
C. 16%
With halved to about 4.8 bits per element and still : . The rate grows much faster than the load, because each of the probes is now more likely to hit a set bit and the probabilities multiply.
A HyperLogLog sketch with registers has a standard error of about . Yours shows about 1.6%. How many times more registers do you need for 0.8%?
- 2 times
- 4 times
- 8 times
- 16 times
Show the answer
B. 4 times
The error scales as , so halving it takes the registers: from registers (about 1.6%) to (about 0.8%). This square-root law is typical of estimators that average independent noisy measurements.
A Count-Min sketch with and has read a stream of items and estimates that item occurred 5,230 times. What do you know about the true count ?
- always, and with probability at least 99%
- exactly
- with probability at least 99%
- with probability at least 99%, with no bound guaranteed on either side
Show the answer
A. always, and with probability at least 99%
Collisions only add to counters, so the estimate is never below the truth. The guarantee bounds the overestimate by with probability at least .
Go deeper
- k-Independence & Tabulation Hashing · How much randomness a hash function really needs.
- Bloom Filters & Their Successors · Set membership with false positives, and cuckoo and xor filters.
- Count-Min, HyperLogLog & Streaming Sketches · Frequency and distinct-count estimates in kilobytes.
Further reading
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 11.
- J. L. Carter & M. N. Wegman, "Universal classes of hash functions," Journal of Computer and System Sciences 18(2) (1979), 143–154.
- B. H. Bloom, "Space/time trade-offs in hash coding with allowable errors," Communications of the ACM 13(7) (1970), 422–426.
- G. Cormode & K. Yi, Small Summaries for Big Data (Cambridge University Press, 2020).