Simple Algorithm
Algorithms & Data Structures · Optimized · 22 min

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 O(1)O(1) 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 ((ax+b) mod p) mod m((ax+b) \bmod p) \bmod m is universal and that it gives an expected chain length of at most 1+α1+\alpha on every input.
  • Derive a Bloom filter's false-positive rate, its best number of hash functions and its cost of about 1.44log⁡2(1/ε)1.44\log_2(1/\varepsilon) 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 O(1)O(1) lookups, but the promise depends on the keys. Fix any hash function hh from a universe UU of possible keys to mm slots. If ∣U∣>(n−1) m\abs{U} > (n-1)\,m, the pigeonhole principle puts at least nn keys of UU into one slot, and whoever knows hh can insert exactly those keys.

With chaining they all join one chain. The ii-th insertion scans the i−1i-1 keys already there to rule out a duplicate, so nn insertions cost 0+1+⋯+(n−1)=n(n−1)/20+1+\dots+(n-1) = n(n-1)/2 key comparisons. For n=105n = 10^5 that is about 5×1095\times10^9 comparisons where you expected about 10510^5.

Universal families

DerivationProof
  1. r≠sr \ne s

    No collisions modulo pp. Fix keys x≠yx \ne y and let r=(ax+b) mod pr = (ax+b) \bmod p and s=(ay+b) mod ps = (ay+b) \bmod p. Then r−s≡a(x−y)(modp)r - s \equiv a(x-y) \pmod p. Neither aa nor x−yx - y is divisible by pp, and pp is prime, so their product is not either:

  2. a=(r−s)(x−y)−1 mod p,b=(r−ax) mod pa = (r - s)(x - y)^{-1} \bmod p, \qquad b = (r - a x) \bmod p

    The pair (r,s)(r, s) is uniformly random. Since x−yx - y has an inverse modulo pp, each pair r≠sr \ne s comes from exactly one (a,b)(a, b). So (a,b)↦(r,s)(a,b) \mapsto (r,s) is a bijection from the p(p−1)p(p-1) functions onto the p(p−1)p(p-1) ordered pairs of distinct residues:

  3. ⌈pm⌉−1 ≤ p+m−1m−1 = p−1m\left\lceil \frac pm \right\rceil - 1 \ \le\ \frac{p + m - 1}{m} - 1 \ =\ \frac{p-1}{m}

    Count the bad pairs. Now h(x)=h(y)h(x) = h(y) exactly when r≡s(modm)r \equiv s \pmod m. For a fixed rr, the values s≠rs \ne r in {0,…,p−1}\{0, \dots, p-1\} with s≡r(modm)s \equiv r \pmod m number at most

  4. Pr⁡[h(x)=h(y)] ≤ (p−1)/mp−1 = 1m\Pr\big[h(x) = h(y)\big] \ \le\ \frac{(p-1)/m}{p-1} \ =\ \frac1m

    Conclude. Given rr, all p−1p - 1 values of ss are equally likely, and at most (p−1)/m(p-1)/m of them cause a collision:

python
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.m

Draw aa and bb 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 261≡1(mod261−1)2^{61} \equiv 1 \pmod{2^{61}-1}. Keys must be integers below pp, 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 SS of nn keys first, then draw hh.

DerivationExpected chain length on every input
  1. Lx=[x∈S]+∑y∈S, y≠xXyL_x = [x \in S] + \sum_{y \in S,\ y \ne x} X_y

    For a key xx, let Xy=1X_y = 1 if h(y)=h(x)h(y) = h(x) and 00 otherwise. The chain that xx hashes to holds xx itself (if x∈Sx \in S) and every other key y∈Sy \in S with Xy=1X_y = 1:

  2. E[Lx] ≤ [x∈S]+n−[x∈S]m ≤ [x∈S]+α\E[L_x] \ \le\ [x \in S] + \frac{n - [x \in S]}{m} \ \le\ [x \in S] + \alpha

    Universality gives E[Xy]=Pr⁡[h(y)=h(x)]≤1/m\E[X_y] = \Pr[h(y) = h(x)] \le 1/m. Linearity of expectation needs no independence between the XyX_y:

  3. E[time of n operations]=O(n)for every sequence of n operations\E\big[\text{time of } n \text{ operations}\big] = O(n)\quad\text{for every sequence of } n \text{ operations}

    So an unsuccessful search scans at most α\alpha keys in expectation and a successful one at most 1+α1 + \alpha, where α=n/m\alpha = n/m is the load factor. Keep α≤1\alpha \le 1 by doubling the table (with a freshly drawn hh) and every operation costs O(1)O(1) expected time, amortized over the resizes:

Two pieces of fine print. First, the bound is an expectation over hh: an unlucky draw can still make one chain long, but no input can force it. Second, the input must not depend on hh. An attacker who can probe the table, for instance by timing lookups, may learn about hh and then choose colliding keys after all.

Check your understanding

A server stores user-supplied keys in a chained hash table. It draws hh 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?

  1. Each operation still takes O(1+α)O(1+\alpha) expected time, because universality holds for every input
  2. The guarantee no longer applies: keys chosen after observing hh's behavior can pile into one slot
  3. The attacker learns nothing, because hh was drawn at random
  4. 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 hh's behavior can pile into one slot

The proof fixes the keys first and then draws hh, so every key must be independent of hh. Timing leaks information about hh, 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 hh when chains grow too long, or both (see the Optimal lesson Hash Flooding & Anti-Hash Tests).

Familyh(x)h(x)GuaranteeCost
Carter–Wegman((ax+b) mod p) mod m((ax+b) \bmod p) \bmod muniversala multiplication and a reduction mod pp
Multiply-shift (Dietzfelbinger et al., 1997)(ax mod 2w)≫(w−ℓ)(a x \bmod 2^w) \gg (w-\ell), aa odd, m=2ℓm = 2^\ellPr⁡[collision]≤2/m\Pr[\text{collision}] \le 2/mone multiplication and one shift
Polynomial of degree k−1k-1(∑i<kaixi mod p) mod m(\sum_{i<k} a_i x^i \bmod p) \bmod mkk-independentkk multiplications
Simple tabulation (Zobrist, 1970)XOR of random table entries, one per byte of xx3-independent, yet behaves like a random function for linear probingone table lookup per byte
SipHash (Aumasson & Bernstein, 2012)a keyed pseudorandom functioncollisions 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
The Optimal lesson k-Independence & Tabulation Hashing proves which guarantee each application needs.

Bloom filters: membership in a few bits per key

Sometimes even a hash table is too big. A web crawler that has seen 101010^{10} 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 mm bits, all 0 at first, with kk hash functions. To insert xx, set the bits h1(x),…,hk(x)h_1(x), \dots, h_k(x) to 1. To query xx, look at those kk bits. If any of them is 0, then xx was never inserted, for certain. If all are 1, then xx is probably present: other keys may have set those bits, which is a false positive.

python
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 n=104n = 10^4 and ε=1%\varepsilon = 1\% this allocates m=95,851m = 95{,}851 bits and k=7k = 7 functions. Two hash values give all kk positions as h1+i h2h_1 + i\,h_2 (Kirsch & Mitzenmacher, 2006) with the same asymptotic false-positive rate as kk independent functions. Use a stable hash such as hashlib: Python's built-in hash() of a string changes from one run to the next.

DerivationThe false-positive rate and the best k
  1. q=(1−1m)kn≈e−kn/mq = \left(1 - \tfrac1m\right)^{kn} \approx e^{-kn/m}

    Model each hi(x)h_i(x) as uniform and independent. After nn insertions, a given bit has escaped all knkn bit settings with probability

  2. ε≈(1−q)k=(1−e−kn/m)k\varepsilon \approx (1 - q)^k = \left(1 - e^{-kn/m}\right)^k

    A key that was never inserted is reported present when all kk of its bits are 1. Treating those kk bits as independent, a slight approximation that the Optimal lesson makes exact:

  3. k∗=mnln⁡2,ε=2−k∗≈0.6185 m/nk^* = \frac mn \ln 2, \qquad \varepsilon = 2^{-k^*} \approx 0.6185^{\,m/n}

    More functions test more bits but also fill the array faster. Substitute k=mnln⁡1qk = \tfrac mn \ln\tfrac1q: the exponent ln⁡ε=−mnln⁡q ln⁡(1−q)\ln\varepsilon = -\tfrac mn \ln q\,\ln(1-q) is symmetric under q↔1−qq \leftrightarrow 1-q and smallest at q=12q = \tfrac12, when half the bits are set:

  4. mn=log⁡2(1/ε)ln⁡2≈1.44 log⁡21ε bits\frac mn = \frac{\log_2(1/\varepsilon)}{\ln 2} \approx 1.44\,\log_2\frac1\varepsilon \ \text{bits}

    Solve for the space. Each element costs, whatever it is (a URL, an IP address, a DNA fragment),

Predict before you look

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

1.44×log⁡2100≈1.44×6.64≈9.61.44 \times \log_2 100 \approx 1.44 \times 6.64 \approx 9.6 bits, with k∗=9.6ln⁡2≈6.6k^* = 9.6 \ln 2 \approx 6.6, 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 ε\varepsilonBits per elementBest kk (rounded)
10%4.83
1%9.67
0.1%14.410
0.01%19.213
A hash set of 64-bit keys spends at least 64 bits per key. No structure with false-positive rate ε\varepsilon can use fewer than log⁡2(1/ε)\log_2(1/\varepsilon) bits per element, so a Bloom filter pays about 44% over the minimum; the Optimal lesson Bloom Filters & Their Successors proves the bound and meets filters that close part of the gap.

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 xx touches holds fxf_x plus whatever collided with xx in that row, so f^x≥fx\hat f_x \ge f_x: a Count-Min sketch never underestimates. With w=⌈e/ε⌉w = \lceil e/\varepsilon \rceil columns and d=⌈ln⁡(1/δ)⌉d = \lceil \ln(1/\delta) \rceil rows, the overestimate exceeds εN\varepsilon N, where NN is the length of the stream, with probability at most δ\delta. For ε=0.1%\varepsilon = 0.1\% and δ=1%\delta = 1\% that is 2,719×52{,}719 \times 5 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 nn distinct hashes, the longest run of leading zeros is about log⁡2n\log_2 n, because a given hash starts with rr zeros with probability 2−r2^{-r}. A single maximum is a noisy estimate, so HyperLogLog (Flajolet, Fusy, Gandouet & Meunier, 2007) splits the hashes among mm registers, keeps the maximum in each and combines them with a harmonic mean. Its standard error is about 1.04/m1.04/\sqrt m: 2142^{14} registers of 6 bits, 12 KB in all, give about 0.8%, and duplicates never change a register.

QuestionExact answerSketchMemory of the sketch
Is xx in the set?hash set: every element storedBloom filter: false positives at rate ε\varepsilon1.44log⁡2(1/ε)1.44\log_2(1/\varepsilon) bits per element
How often did xx occur?hash map: one counter per distinct itemCount-Min: overestimate ≤εN\le \varepsilon N with probability ≥1−δ\ge 1-\delta⌈e/ε⌉⋅⌈ln⁡(1/δ)⌉\lceil e/\varepsilon\rceil \cdot \lceil \ln(1/\delta)\rceil counters
How many distinct items?hash set: every distinct item storedHyperLogLog: standard error ≈1.04/m\approx 1.04/\sqrt mmm 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.
ProblemKey ideaCost
A crawler must never fetch a URL twice, across billions of URLsA Bloom filter of visited URLs; a false positive only skips one pageabout 9.6 bits per URL at 1%, kk bit probes per query
Distinct visitors per page per day, logged by many serversOne HyperLogLog per page and server, merged by register maxima12 KB per counter for about 0.8% error
The most frequent search queries in an endless streamCount-Min estimates plus a min-heap of the current top kk (or the deterministic Misra–Gries summary)O(1εlog⁡1δ)O(\tfrac1\varepsilon\log\tfrac1\delta) counters, O(log⁡1δ+log⁡k)O(\log\tfrac1\delta + \log k) per item
A web server builds hash tables from request parametersA keyed hash with a secret random seed, so no one can aim at a slotO(1)O(1) expected per operation
Counting equal pairs among 10610^6 integers in a contest where others may submit hacking testsA hash map with a randomized hash function, drawn at run timeO(n)O(n) expected
The heap-based top-kk and Misra–Gries appear in the Optimal lesson Top-k, Heavy Hitters & Streaming Quantiles.

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 pp, or a modulus that is not prime: universality is silently lost.
  • Sizing a Bloom filter for nn elements, then inserting 2n2n: 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 2322^{32} distinct items. Use 64-bit hashes.
Check your understanding

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?

  1. A hash set of addresses per router, merged at the dashboard
  2. A Count-Min sketch per router, adding up its counters
  3. A HyperLogLog per router, merged by register maxima
  4. 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 hh from a universal family, with Pr⁡[h(x)=h(y)]≤1/m\Pr[h(x) = h(y)] \le 1/m, makes the expected chain length at most 1+α1+\alpha for every input fixed independently of hh.
  • ((ax+b) mod p) mod m((ax+b) \bmod p) \bmod m with a prime pp is universal; multiply-shift is the fast practical choice, with collision probability at most 2/m2/m. Adaptive attackers who learn hh break the guarantee, so servers use keyed hashes such as SipHash.
  • A Bloom filter with k=(m/n)ln⁡2k = (m/n)\ln 2 hash functions has a false-positive rate of about 0.6185m/n0.6185^{m/n}: roughly 1.44log⁡2(1/ε)1.44\log_2(1/\varepsilon) bits per element, no false negatives and no deletions.
  • Sketches trade exactness for memory: Count-Min overestimates a frequency by at most εN\varepsilon N with probability 1−δ1-\delta, and HyperLogLog counts distinct items with standard error about 1.04/m1.04/\sqrt m. Both merge across machines.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A table stores keys chosen by an adversary who knows your code but not your random bits. You draw hh from a universal family when the table is created. What is guaranteed?

  1. No two keys ever collide
  2. Every lookup takes O(1)O(1) time in the worst case
  3. For every set of keys fixed in advance, each lookup takes O(1+α)O(1+\alpha) expected time
  4. Lookups take O(1)O(1) time on average, provided the keys are random
Show the answer

C. For every set of keys fixed in advance, each lookup takes O(1+α)O(1+\alpha) expected time

Universality bounds each pair's collision probability by 1/m1/m, so the expected chain length is at most 1+α1+\alpha for any key set chosen independently of hh. The expectation is over hh, not over the keys.

Question 2

Where does the proof that ((ax+b) mod p) mod m((ax+b) \bmod p) \bmod m is universal use that pp is prime?

  1. To make mm divide p−1p - 1
  2. To make the final reduction mod mm uniform
  3. Nowhere: any modulus larger than the keys works
  4. To show that a(x−y)≢0(modp)a(x-y) \not\equiv 0 \pmod p and that x−yx - y has an inverse modulo pp
Show the answer

D. To show that a(x−y)≢0(modp)a(x-y) \not\equiv 0 \pmod p and that x−yx - y has an inverse modulo pp

Modulo a prime there are no zero divisors, so a≠0a \ne 0 and x≠yx \ne y give r≠sr \ne s, and x−yx - y is invertible, which makes (a,b)↦(r,s)(a,b) \mapsto (r,s) a bijection. With p=12p = 12, a=6a = 6 and x−y=2x - y = 2, the keys would collide modulo pp already.

Question 3

A Bloom filter was sized for n=106n = 10^6 elements at a 1% false-positive rate (about 9.6n9.6n bits, k=7k = 7). By mistake, 2×1062 \times 10^6 elements are inserted. About what is its false-positive rate now?

  1. 2%
  2. 4%
  3. 16%
  4. 50%
Show the answer

C. 16%

With m/nm/n halved to about 4.8 bits per element and still k=7k = 7: (1−e−7/4.79)7≈0.7687≈0.16(1 - e^{-7/4.79})^7 \approx 0.768^7 \approx 0.16. The rate grows much faster than the load, because each of the kk probes is now more likely to hit a set bit and the probabilities multiply.

Question 4

A HyperLogLog sketch with mm registers has a standard error of about 1.04/m1.04/\sqrt m. Yours shows about 1.6%. How many times more registers do you need for 0.8%?

  1. 2 times
  2. 4 times
  3. 8 times
  4. 16 times
Show the answer

B. 4 times

The error scales as 1/m1/\sqrt m, so halving it takes 4×4\times the registers: from 2122^{12} registers (about 1.6%) to 2142^{14} (about 0.8%). This square-root law is typical of estimators that average independent noisy measurements.

Question 5

A Count-Min sketch with ε=0.1%\varepsilon = 0.1\% and δ=1%\delta = 1\% has read a stream of N=106N = 10^6 items and estimates that item xx occurred 5,230 times. What do you know about the true count fxf_x?

  1. fx≤5,230f_x \le 5{,}230 always, and fx≥4,230f_x \ge 4{,}230 with probability at least 99%
  2. fx=5,230f_x = 5{,}230 exactly
  3. 5,230≤fx≤6,2305{,}230 \le f_x \le 6{,}230 with probability at least 99%
  4. 4,230≤fx≤6,2304{,}230 \le f_x \le 6{,}230 with probability at least 99%, with no bound guaranteed on either side
Show the answer

A. fx≤5,230f_x \le 5{,}230 always, and fx≥4,230f_x \ge 4{,}230 with probability at least 99%

Collisions only add to counters, so the estimate is never below the truth. The guarantee bounds the overestimate by εN=1,000\varepsilon N = 1{,}000 with probability at least 1−δ=99%1 - \delta = 99\%.

Go deeper

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).