Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

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 O(n)O(n) expected space with O(1)O(1) 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 nlog⁡2e≈1.44nn \log_2 e \approx 1.44n-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 SS of nn keys we want lookups that cost O(1)O(1) in the worst case. A perfect hash function for SS is one with no collisions on SS.

The birthday paradox, read backwards, gives one cheaply but wastefully: hash SS with a random function from a universal family into n2n^2 slots. The expected number of colliding pairs is at most (n2)/n2<12\binom n2 / n^2 < \tfrac12, so by Markov's inequality a random draw is collision-free with probability more than 12\tfrac12. Quadratic space is too much for one level, but it is the right size for many small buckets, and that is the FKS scheme.

DerivationProof: the FKS scheme
  1. ∑ini2=n+2C,E[C]≤(n2)⋅1n=n−12⟹E[∑ini2]<2n\sum_i n_i^2 = n + 2C, \qquad \E[C] \le \binom n2 \cdot \frac1n = \frac{n-1}{2} \quad\Longrightarrow\quad \E\Big[\sum_i n_i^2\Big] < 2n

    Level 1. Draw hh from a universal family into m=nm = n buckets; bucket ii receives nin_i keys. Count pairs: ni2=ni+2(ni2)n_i^2 = n_i + 2\binom{n_i}{2}, so with CC the number of colliding pairs,

  2. Pr⁡[∑ini2≥4n]≤E[∑ini2]4n<12\Pr\Big[\sum_i n_i^2 \ge 4n\Big] \le \frac{\E[\sum_i n_i^2]}{4n} < \frac12

    Retry if unlucky. By Markov's inequality, Pr⁡[∑ini2≥4n]<12\Pr[\sum_i n_i^2 \ge 4n] < \tfrac12, so an expected 2 draws give ∑ini2<4n\sum_i n_i^2 < 4n.

  3. Pr⁡[hi has a collision]≤(ni2)⋅1ni2<12\Pr[h_i \text{ has a collision}] \le \binom{n_i}{2} \cdot \frac{1}{n_i^2} < \frac12

    Level 2. Give bucket ii a table of ni2n_i^2 slots and draw a universal hih_i until it is injective on the bucket's keys. Each draw fails with probability at most (ni2)/ni2<12\binom{n_i}{2}/n_i^2 < \tfrac12, so expected 2 draws per bucket, O(ni2)O(n_i^2) time each.

  4. space=O(n),lookup=2 hashes+1 comparison\text{space} = O(n), \qquad \text{lookup} = 2 \text{ hashes} + 1 \text{ comparison}

    Cost. Space: nn bucket headers (two parameters each) plus ∑ini2<4n\sum_i n_i^2 < 4n slots. A lookup for xx computes i=h(x)i = h(x), then hi(x)h_i(x), and compares one key: two hash evaluations, always.

python
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)] == x

Tested on random sets of up to 20,000 keys: every key is found, non-keys are rejected, and the second level used about 2n2n slots, as E[∑ini2]=2n−1\E[\sum_i n_i^2] = 2n - 1 for truly random functions predicts.

Check your understanding

Why does FKS give a bucket with nin_i keys a table of ni2n_i^2 slots rather than, say, 2ni2n_i?

  1. With ni2n_i^2 slots a random universal function is collision-free with probability above 12\tfrac12, and the total ∑ini2\sum_i n_i^2 is still O(n)O(n) in expectation
  2. Squaring makes the lookup cost O(log⁡ni)O(\log n_i) instead of O(ni)O(n_i)
  3. Any table with more than nin_i slots is collision-free
  4. It is wasteful; 2ni2n_i slots would give the same guarantees
Show the answer

A. With ni2n_i^2 slots a random universal function is collision-free with probability above 12\tfrac12, and the total ∑ini2\sum_i n_i^2 is still O(n)O(n) in expectation

The birthday bound needs about ni2n_i^2 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 ∑ini2<4n\sum_i n_i^2 < 4n 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 O(1)O(1) lookups. It uses two tables T1T_1, T2T_2 of rr slots each and two hash functions, with one invariant: every key xx is in T1[h1(x)]T_1[h_1(x)] or in T2[h2(x)]T_2[h_2(x)]. A lookup reads those two slots, and a deletion empties one of them.

To insert xx, put it in T1[h1(x)]T_1[h_1(x)]. If a key yy was there, yy is evicted and moves to its slot in the other table, possibly evicting zz, 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 3log⁡1+εr3\log_{1+\varepsilon} r moves), the insertion gives up: draw new hash functions and rehash everything.

python
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 all

When 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 r=10,000r = 10{,}000, every one of 40 tables filled to 45% of the 2r2r slots was built without giving up; at 52% most failed.

DerivationWhy one half, and why Θ(1/n)
  1. average degree=2n2r<1  ⟺  load=n2r<12\text{average degree} = \frac{2n}{2r} < 1 \iff \text{load} = \frac{n}{2r} < \frac12

    The cuckoo graph is a random bipartite multigraph with 2r2r vertices and nn edges, so its average degree is 2n/(2r)=2⋅load2n/(2r) = 2\cdot\text{load}. 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.

  2. E[evictions]≤2 E[ ∣component of x∣ ]=O(1)\E[\text{evictions}] \le 2\,\E\big[\,|\text{component of } x|\,\big] = O(1)

    Below the threshold an insertion's walk stays inside its component, whose expected size is O(1)O(1); that gives the expected O(1)O(1) insertion time.

  3. Pr⁡[some three keys share both slots]≈(n3)⋅1r4=Θ(1n)\Pr[\text{some three keys share both slots}] \approx \binom n3 \cdot \frac{1}{r^4} = \Theta\Big(\frac1n\Big)

    Failure cannot be rarer than order 1/n1/n: three keys that share both slots form a component with 2 vertices and 3 edges. For r=Θ(n)r = \Theta(n),

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 d≥3d \ge 3 possible slots (dd-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.

VariantLoad thresholdProbes per lookup
2 choices, 1 slot each (Pagh & Rodler)0.50.52 slots
3 choices, 1 slot each≈0.918\approx 0.9183 slots
4 choices, 1 slot each≈0.977\approx 0.9774 slots
2 choices, buckets of 2 slots≈0.897\approx 0.8972 buckets (4 slots)
2 choices, buckets of 4 slots≈0.980\approx 0.9802 buckets (8 slots)
The thresholds for dd choices equal those of random dd-XORSAT (Dietzfelbinger, Goerdt, Mitzenmacher, Montanari, Pagh & Rink, 2010, and independent work). All five were checked numerically for this lesson, by testing with a maximum matching whether random instances just below and just above each threshold can be placed. A bucket of 4 small slots fits in one cache line, and the cuckoo filters of the Optimal lesson Bloom Filters & Their Successors use such buckets to reach about 95% load.
Predict before you look

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 c3∗≈0.9179c_3^* \approx 0.9179. 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 Θ(1/n)\Theta(1/n) per build, too often for a table that lives through billions of insertions. Kirsch, Mitzenmacher & Wieder (2008) added a stash: a tiny array of ss keys, checked on every lookup, that holds keys the insertion could not place. They proved that with a stash of constant size ss a rehash is needed only with probability O(n−(s+1))O(n^{-(s+1)}), and in their experiments a stash of 4 keys pushed the rehash rate below 10−610^{-6}. A stash does not change the expected insertion time; it only makes the rare bad events far rarer.

How random must h1h_1 and h2h_2 be? Pagh and Rodler assumed highly independent functions. Simple tabulation suffices, with failure probability O(n−1/3)O(n^{-1/3}) (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

DerivationProof by counting
  1. ∏iui ≤ (un)n  sets\prod_{i} u_i \ \le\ \Big(\frac un\Big)^{n} \ \text{ sets}

    Fix one function f:U→{0,…,n−1}f: U \to \{0, \dots, n-1\} with preimages of sizes u0,…,un−1u_0, \dots, u_{n-1}. It is one-to-one on SS exactly when SS takes one key from each preimage, so by the AM–GM inequality it serves at most

  2. #functions ≥ (un)/(un)n ≈ un/n!(u/n)n=nnn!\#\text{functions} \ \ge\ \binom un \Big/ \Big(\frac un\Big)^{n} \ \approx\ \frac{u^n/n!}{(u/n)^n} = \frac{n^n}{n!}

    A family that contains an MPHF for every one of the (un)\binom un sets must therefore have at least

  3. log⁡2#functions ≥ nlog⁡2e−12log⁡2(2πn) ≈ 1.4427 n bits\log_2 \#\text{functions} \ \ge\ n\log_2 e - \tfrac12 \log_2(2\pi n) \ \approx\ 1.4427\,n \text{ bits}

    By Stirling's formula n!≈2πn (n/e)nn! \approx \sqrt{2\pi n}\,(n/e)^n, so the count is about en/2πne^n/\sqrt{2\pi n}, and naming one member takes

ConstructionBits per keyIdea
FKS (1984)O(1)O(1) machine words per keyTwo levels of universal hashing, as above
CHD, "hash, displace, and compress" (Belazzougui, Botelho & Dietzfelbinger, 2009)2.07 in its experimentsHash 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 boundSplit the keys recursively into small leaves, and brute-force a bijective hash function for each leaf
Lower boundlog⁡2e≈1.44\log_2 e \approx 1.44The counting argument above
Evaluation stays O(1)O(1) throughout; what costs more as the space approaches the bound is construction time.

Key takeaways

  • FKS stores a static set in O(n)O(n) space with two-probe worst-case lookups: universal hashing into nn buckets gives E[∑ini2]<2n\E[\sum_i n_i^2] < 2n, and each bucket gets a collision-free table of ni2n_i^2 slots.
  • Cuckoo hashing keeps every key in one of two slots, so lookups and deletions take O(1)O(1) worst-case time; insertions evict residents and take O(1)O(1) expected time while the load stays below 12\tfrac12.
  • Insertion fails exactly when a component of the cuckoo graph has two cycles, which happens with probability Θ(1/n)\Theta(1/n); a stash of ss keys cuts it to O(n−(s+1))O(n^{-(s+1)}).
  • 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 nlog⁡2e≈1.44nn\log_2 e \approx 1.44n 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.

Question 1

In FKS, the first-level function is drawn from a universal family into m=nm = n buckets. What bounds the expected total size E[∑ini2]\E[\sum_i n_i^2] of the second-level tables?

  1. n\sqrt n
  2. Less than 2n2n
  3. About nlog⁡nn \log n
  4. About n2/2n^2/2
Show the answer

B. Less than 2n2n

∑ini2=n+2C\sum_i n_i^2 = n + 2C, where CC counts colliding pairs, and universality gives E[C]≤(n2)/n=(n−1)/2\E[C] \le \binom n2/n = (n-1)/2. So E[∑ini2]≤2n−1\E[\sum_i n_i^2] \le 2n - 1.

Question 2

In a cuckoo table, three keys aa, bb, cc all have h1=3h_1 = 3 and h2=5h_2 = 5. What happens when the third one is inserted?

  1. It evicts one of the others, which moves to its other slot, and all three end up placed
  2. The insertion cycles until it gives up, and the table must be rehashed with new functions
  3. The third key goes to the next free slot of T1T_1
  4. Lookups for aa and bb 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 T1[3]T_1[3] and T2[5]T_2[5] until it hits its limit; only new hash functions (or a stash) can help.

Question 3

What does adding a stash of constant size ss to cuckoo hashing change?

  1. The load threshold rises from 12\tfrac12 to about 0.90.9
  2. Lookups no longer need to read two table slots
  3. The expected insertion time drops from O(log⁡n)O(\log n) to O(1)O(1)
  4. The probability that the table must be rebuilt drops from Θ(1/n)\Theta(1/n) to O(n−(s+1))O(n^{-(s+1)}), at the cost of checking the stash on lookups
Show the answer

D. The probability that the table must be rebuilt drops from Θ(1/n)\Theta(1/n) to O(n−(s+1))O(n^{-(s+1)}), 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 ss stash slots overflow only with probability O(n−(s+1))O(n^{-(s+1)}). The threshold and the expected insertion time are unchanged.

Question 4

About how much memory must a minimal perfect hash function for 10910^9 keys occupy at the very least?

  1. About 125 megabytes, one bit per key
  2. About 180 megabytes
  3. About 1.44 gigabytes
  4. About 4 gigabytes, one 32-bit index per key
Show the answer

B. About 180 megabytes

109log⁡2e≈1.44×10910^9 \log_2 e \approx 1.44 \times 10^9 bits, which is about 1.8×1081.8 \times 10^8 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 O(1)O(1) 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).