Cuckoo Hashing & Perfect Hashing
Worst-case O(1) lookups: two choices, FKS and minimal perfect hashing.
Every table so far has a bad case: a long chain or a long probe sequence. Cuckoo hashing promises that a lookup reads at most two slots, always, by giving each key two possible homes and letting a newcomer evict a resident, as a cuckoo chick pushes eggs out of a nest. And when the keys are known in advance you can go further: a hash function with no collisions at all, stored in under two bits per key.
What you’ll learn
- Build the FKS two-level perfect hash table, and prove that it uses expected space with worst-case lookups.
- Implement cuckoo hashing, and explain its successes and failures with the cuckoo graph: insertion succeeds exactly when no component has two cycles.
- State the load thresholds of cuckoo hashing with two choices, more choices and larger buckets, and what a stash buys.
- Prove the -bit lower bound for minimal perfect hashing, and place CHD and RecSplit against it.
Static sets: FKS perfect hashing
Many key sets never change once built: a compiler's reserved words, a dictionary shipped with a product, an immutable database index. For such a static set of keys we want lookups that cost in the worst case. A perfect hash function for is one with no collisions on .
The birthday paradox, read backwards, gives one cheaply but wastefully: hash with a random function from a universal family into slots. The expected number of colliding pairs is at most , so by Markov's inequality a random draw is collision-free with probability more than . Quadratic space is too much for one level, but it is the right size for many small buckets, and that is the FKS scheme.
Level 1. Draw from a universal family into buckets; bucket receives keys. Count pairs: , so with the number of colliding pairs,
Retry if unlucky. By Markov's inequality, , so an expected 2 draws give .
Level 2. Give bucket a table of slots and draw a universal until it is injective on the bucket's keys. Each draw fails with probability at most , so expected 2 draws per bucket, time each.
Cost. Space: bucket headers (two parameters each) plus slots. A lookup for computes , then , and compares one key: two hash evaluations, always.
import random
P = (1 << 61) - 1 # a prime above every key
def draw(m): # a random member of the Carter-Wegman family
a, b = random.randrange(1, P), random.randrange(P)
return lambda x: ((a * x + b) % P) % m
def build_fks(keys):
n = len(keys)
while True: # level 1: retry until sum of n_i^2 <= 4n
h = draw(n)
buckets = [[] for _ in range(n)]
for x in keys:
buckets[h(x)].append(x)
if sum(len(b) ** 2 for b in buckets) <= 4 * n:
break
tables = []
for b in buckets: # level 2: n_i^2 slots, retry until injective
while True:
g = draw(len(b) ** 2) if b else None
t = [None] * (len(b) ** 2)
for x in b:
if t[g(x)] is not None:
break
t[g(x)] = x
else:
tables.append((g, t))
break
return h, tables
def contains(fks, x): # two hash evaluations, one comparison
h, tables = fks
g, t = tables[h(x)]
return bool(t) and t[g(x)] == xTested on random sets of up to 20,000 keys: every key is found, non-keys are rejected, and the second level used about slots, as for truly random functions predicts.
Why does FKS give a bucket with keys a table of slots rather than, say, ?
- With slots a random universal function is collision-free with probability above , and the total is still in expectation
- Squaring makes the lookup cost instead of
- Any table with more than slots is collision-free
- It is wasteful; slots would give the same guarantees
Show the answer
A. With slots a random universal function is collision-free with probability above , and the total is still in expectation
The birthday bound needs about slots before collisions become unlikely, which keeps the expected number of retries at most 2. Level 1 is chosen so that buckets are small on average, making after an expected 2 draws.
Cuckoo hashing: two choices and evictions
FKS needs the keys in advance. Cuckoo hashing (Pagh & Rodler, 2001) is dynamic and keeps worst-case lookups. It uses two tables , of slots each and two hash functions, with one invariant: every key is in or in . A lookup reads those two slots, and a deletion empties one of them.
To insert , put it in . If a key was there, is evicted and moves to its slot in the other table, possibly evicting , which moves back, and so on until a key lands in an empty slot. If the chain of evictions grows too long (Pagh and Rodler stop after about moves), the insertion gives up: draw new hash functions and rehash everything.
import math, random
P = (1 << 61) - 1
class CuckooSet:
"""Key x lives in T[0][h(0, x)] or in T[1][h(1, x)]: a lookup reads at most 2 slots."""
def __init__(self, r):
self.r, self.T = r, [[None] * r, [None] * r]
self.ab = [(random.randrange(1, P), random.randrange(P)) for _ in range(2)]
self.max_loop = 6 * math.ceil(math.log2(r)) # cap on evictions per insertion
def h(self, i, x):
a, b = self.ab[i]
return ((a * x + b) % P) % self.r
def __contains__(self, x):
return self.T[0][self.h(0, x)] == x or self.T[1][self.h(1, x)] == x
def add(self, x): # None on success, else the key left homeless
if x in self:
return None
i = 0
for _ in range(self.max_loop):
j = self.h(i, x)
x, self.T[i][j] = self.T[i][j], x # put x in its slot, pick up the evicted key
if x is None:
return None
i = 1 - i # the evicted key moves to its other table
return x # give up: draw new functions, rehash allWhen add gives up, the key it returns may not be the one you inserted: it is whichever key was left without a slot, and a real table reinserts it together with everything else under new hash functions. In tests with , every one of 40 tables filled to 45% of the slots was built without giving up; at 52% most failed.
The cuckoo graph is a random bipartite multigraph with vertices and edges, so its average degree is . Random graphs change character at average degree 1: below it, components are small trees and a few single cycles; above it, a giant component full of cycles appears.
Below the threshold an insertion's walk stays inside its component, whose expected size is ; that gives the expected insertion time.
Failure cannot be rarer than order : three keys that share both slots form a component with 2 vertices and 3 edges. For ,
More choices, bigger buckets, a stash
Half-empty tables are the price of two choices with one key per slot. Two generalizations raise the load: give each key possible slots (-ary cuckoo hashing), or let each of the two choices be a bucket of several slots (blocked cuckoo hashing, Dietzfelbinger & Weidling). With truly random hash functions the thresholds are sharp: below them all keys fit with high probability, above them almost surely not.
| Variant | Load threshold | Probes per lookup |
|---|---|---|
| 2 choices, 1 slot each (Pagh & Rodler) | 2 slots | |
| 3 choices, 1 slot each | 3 slots | |
| 4 choices, 1 slot each | 4 slots | |
| 2 choices, buckets of 2 slots | 2 buckets (4 slots) | |
| 2 choices, buckets of 4 slots | 2 buckets (8 slots) |
With three hash functions and one key per slot, up to what fraction of the slots can a cuckoo table be filled before insertions start to fail (in percent)?
Show the answer
91.8 %
About 91.8%: the threshold . A third choice nearly doubles the usable space compared with two choices (50%), and a fourth brings it to about 97.7%. The price is one more slot to read on every lookup, and an insertion procedure (random walk or breadth-first search) that is harder to analyze.
A stash. Standard cuckoo hashing fails with probability per build, too often for a table that lives through billions of insertions. Kirsch, Mitzenmacher & Wieder (2008) added a stash: a tiny array of keys, checked on every lookup, that holds keys the insertion could not place. They proved that with a stash of constant size a rehash is needed only with probability , and in their experiments a stash of 4 keys pushed the rehash rate below . A stash does not change the expected insertion time; it only makes the rare bad events far rarer.
How random must and be? Pagh and Rodler assumed highly independent functions. Simple tabulation suffices, with failure probability (see k-Independence & Tabulation Hashing), and with a stash, simple explicit families built from 2-independent functions provably work (Aumüller, Dietzfelbinger & Woelfel, 2014).
Minimal perfect hashing
Fix one function with preimages of sizes . It is one-to-one on exactly when takes one key from each preimage, so by the AM–GM inequality it serves at most
A family that contains an MPHF for every one of the sets must therefore have at least
By Stirling's formula , so the count is about , and naming one member takes
| Construction | Bits per key | Idea |
|---|---|---|
| FKS (1984) | machine words per key | Two levels of universal hashing, as above |
| CHD, "hash, displace, and compress" (Belazzougui, Botelho & Dietzfelbinger, 2009) | 2.07 in its experiments | Hash keys to small buckets; for each bucket, from the largest down, find a displacement that sends all its keys to free slots; compress the displacements |
| RecSplit (Esposito, Mueller Graf & Vigna, 2020) | 1.56, within 8.3% of the bound | Split the keys recursively into small leaves, and brute-force a bijective hash function for each leaf |
| Lower bound | The counting argument above |
Key takeaways
- FKS stores a static set in space with two-probe worst-case lookups: universal hashing into buckets gives , and each bucket gets a collision-free table of slots.
- Cuckoo hashing keeps every key in one of two slots, so lookups and deletions take worst-case time; insertions evict residents and take expected time while the load stays below .
- Insertion fails exactly when a component of the cuckoo graph has two cycles, which happens with probability ; a stash of keys cuts it to .
- More choices or bigger buckets raise the threshold: about 0.918 with three choices, 0.977 with four, 0.897 and 0.980 with two buckets of 2 or 4 slots.
- A minimal perfect hash function needs at least bits; CHD uses about 2.07 bits per key and RecSplit about 1.56.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In FKS, the first-level function is drawn from a universal family into buckets. What bounds the expected total size of the second-level tables?
- Less than
- About
- About
Show the answer
B. Less than
, where counts colliding pairs, and universality gives . So .
In a cuckoo table, three keys , , all have and . What happens when the third one is inserted?
- It evicts one of the others, which moves to its other slot, and all three end up placed
- The insertion cycles until it gives up, and the table must be rehashed with new functions
- The third key goes to the next free slot of
- Lookups for and now need three probes
Show the answer
B. The insertion cycles until it gives up, and the table must be rehashed with new functions
The three keys are three edges between the same two vertices: a component with 3 edges and 2 vertices, which no placement can satisfy. The eviction walk bounces between and until it hits its limit; only new hash functions (or a stash) can help.
What does adding a stash of constant size to cuckoo hashing change?
- The load threshold rises from to about
- Lookups no longer need to read two table slots
- The expected insertion time drops from to
- The probability that the table must be rebuilt drops from to , at the cost of checking the stash on lookups
Show the answer
D. The probability that the table must be rebuilt drops from to , at the cost of checking the stash on lookups
The stash absorbs the few keys involved in rare bad configurations of the cuckoo graph, such as three keys sharing two slots. Kirsch, Mitzenmacher and Wieder proved that stash slots overflow only with probability . The threshold and the expected insertion time are unchanged.
About how much memory must a minimal perfect hash function for keys occupy at the very least?
- About 125 megabytes, one bit per key
- About 180 megabytes
- About 1.44 gigabytes
- About 4 gigabytes, one 32-bit index per key
Show the answer
B. About 180 megabytes
bits, which is about bytes: roughly 180 MB. RecSplit's 1.56 bits per key would need about 195 MB.
Further reading
- M. L. Fredman, J. Komlós & E. Szemerédi, "Storing a sparse table with worst case access time," Journal of the ACM 31(3) (1984), 538–544.
- R. Pagh & F. F. Rodler, "Cuckoo hashing," Proceedings of ESA 2001, LNCS 2161; journal version in Journal of Algorithms 51(2) (2004).
- A. Kirsch, M. Mitzenmacher & U. Wieder, "More robust hashing: cuckoo hashing with a stash," Proceedings of ESA 2008.
- E. Esposito, T. Mueller Graf & S. Vigna, "RecSplit: Minimal perfect hashing via recursive splitting," Proceedings of ALENEX (2020); arXiv:1910.06416.
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 3rd ed. (MIT Press, 2009), section 11.5 (perfect hashing).