TExcelTAD

Cuckoo Hashing

Chaining and open addressing give O(1)O(1) expected lookups, but an unlucky key may sit in a long chain or at the end of a long probe sequence; with nn keys in Θ(n)\Theta(n) slots the longest chain is Θ(lg⁡n/lg⁡lg⁡n)\Theta(\lg n / \lg \lg n) with high probability. Cuckoo hashing (Pagh and Rodler, 2001; journal version 2004) guarantees that every lookup reads at most two slots, in the worst case, while insertions take O(1)O(1) expected amortized time. The price is a load factor below 1/21/2 and an insertion procedure that occasionally rebuilds the table.

The structure

Two tables T0T_0 and T1T_1 of rr slots each and two hash functions h0,h1h_0, h_1. Invariant: every key xx is stored either in T0[h0(x)]T_0[h_0(x)] or in T1[h1(x)]T_1[h_1(x)].

  • LOOKUP(x)(x): check those two slots. Two probes, worst case.
  • DELETE(x)(x): find it and clear the slot. Worst case O(1)O(1).
  • INSERT(x)(x): put xx in T0[h0(x)]T_0[h_0(x)]. If the slot was occupied by yy, yy is kicked out (like a cuckoo chick pushing an egg out of the nest) and moves to its other slot, T1[h1(y)]T_1[h_1(y)], possibly kicking out a third key, and so on. If the chain of evictions exceeds a limit of O(lg⁡n)O(\lg n) steps, assume it is cycling: pick new hash functions and rehash everything.
text
INSERT(x)
1  if LOOKUP(x)  return
2  i = 0
3  repeat MAX-LOOP times
4      swap x with T[i][h_i(x)]         // place x, pick up the previous occupant
5      if x == NIL  return              // the slot was free
6      i = 1 - i                        // the evicted key goes to its other table
7  REHASH with new h_0, h_1, then INSERT(x)

The cuckoo graph and the load threshold

Think of the 2r2r slots as vertices and of each key xx as an edge between T0[h0(x)]T_0[h_0(x)] and T1[h1(x)]T_1[h_1(x)]: the cuckoo graph, a random bipartite multigraph. A set of keys can be stored if and only if every connected component of this graph has at most one cycle (a component with vv vertices can hold at most vv keys, one per slot). Insertion walks along the component of the new edge.

For nn random edges on 2r2r vertices, random graph theory says that while n≤(1−ε)rn \le (1 - \varepsilon) r, components are small (logarithmic size) trees or unicyclic with high probability, and a component with two cycles appears with probability O(1/r)O(1/r). At n≈rn \approx r, a giant component appears and failure becomes likely. So the load threshold is

n2r<12\frac{n}{2r} < \frac{1}{2}

Theorem (Pagh and Rodler). If r≥(1+ε)nr \ge (1 + \varepsilon) n for a constant ε>0\varepsilon > 0, and the hash functions are drawn from a family with sufficient independence (O(lg⁡n)O(\lg n)-wise independent suffices for their proof; for practical functions it holds empirically), then INSERT takes O(1)O(1) expected amortized time, including rehashes, and LOOKUP and DELETE take O(1)O(1) worst-case time.

Why insertions are $O(1)$ expected (sketch)

The number of evictions of an insertion is at most the size of the component of the new edge, times 2 (the walk can traverse a cycle and come back). In a random graph with n≤(1−ε)rn \le (1 - \varepsilon) r edges on 2r2r vertices, the probability that a given vertex lies in a component of size at least ss decays exponentially in ss, so the expected walk length is O(1)O(1). A rehash happens only when some component has two cycles, with probability O(1/n)O(1/n) per insertion, and costs O(n)O(n) expected, adding O(1)O(1) to the expectation.

An implementation

The program uses two tables of 5000 slots, seeded splitmix64 hash functions and a rehash on failure. It inserts 4500 keys (load 0.450.45) and reports the average number of evictions per insertion as the load grows.

python · try it yourself
import random

MASK = (1 << 64) - 1
def mix64(x):
    x = (x + 0x9E3779B97F4A7C15) & MASK
    x = ((x ^ (x >> 30)) * 0xBF58476D1CE4E5B9) & MASK
    x = ((x ^ (x >> 27)) * 0x94D049BB133111EB) & MASK
    return x ^ (x >> 31)

class Cuckoo:
    """Cuckoo hashing (Pagh and Rodler): two tables of r slots; x lives in T[0][h0(x)] or T[1][h1(x)]."""
    def __init__(self, r, rng, max_kicks=None):
        self.r, self.rng = r, rng
        self.max_kicks = max_kicks or 6 * max(1, r.bit_length())
        self._new_functions()
        self.T = [[None] * r, [None] * r]
        self.n = self.kicks = self.rehashes = 0
    def _new_functions(self):
        self.seeds = (self.rng.getrandbits(64), self.rng.getrandbits(64))
    def _h(self, i, x):
        return mix64(x ^ self.seeds[i]) % self.r
    def contains(self, x):                          # at most 2 probes, worst case
        return self.T[0][self._h(0, x)] == x or self.T[1][self._h(1, x)] == x
    def insert(self, x):
        if self.contains(x): return True
        i = 0
        for _ in range(self.max_kicks):
            slot = self._h(i, x)
            x, self.T[i][slot] = self.T[i][slot], x  # put x here, pick up the previous occupant
            if x is None:
                self.n += 1; return True
            self.kicks += 1
            i = 1 - i                                # the evicted key goes to its other table
        return False                                 # probably a cycle: caller rehashes
    def rehash_insert(self, x):
        while not self.insert(x):                    # x is the key left homeless
            self.rehashes += 1
            keys = [k for t in self.T for k in t if k is not None] + [x]
            self._new_functions()
            self.T, self.n = [[None] * self.r, [None] * self.r], 0
            x = None
            for k in keys:
                if not self.insert(k):
                    x = k; break                     # failed again: rehash again
            if x is None: return

rng = random.Random(2001)
r = 5000                                             # 10000 slots in total
c = Cuckoo(r, rng)
keys = rng.sample(range(10 ** 9), int(0.45 * 2 * r))
checkpoints = {int(f * 2 * r): f for f in [0.1, 0.2, 0.3, 0.4, 0.45]}
for j, x in enumerate(keys, 1):
    c.rehash_insert(x)
    if j in checkpoints:
        print(f"load {checkpoints[j]:.2f}: {c.kicks / j:.3f} evictions per insert so far, rehashes {c.rehashes}")
assert all(c.contains(x) for x in keys)
absent = sum(c.contains(x) for x in range(10 ** 9, 10 ** 9 + 20000))
print(f"{len(keys)} keys stored, every lookup probes at most 2 slots; false hits on 20000 absent keys: {absent}")
load 0.10: 0.109 evictions per insert so far, rehashes 0
load 0.20: 0.200 evictions per insert so far, rehashes 0
load 0.30: 0.308 evictions per insert so far, rehashes 0
load 0.40: 0.465 evictions per insert so far, rehashes 0
load 0.45: 0.556 evictions per insert so far, rehashes 0
4500 keys stored, every lookup probes at most 2 slots; false hits on 20000 absent keys: 0

Evictions stay below one per insertion on average, growing as the load approaches the threshold. The next program fills tables until the first failure (no rehashing), for three table sizes and five random runs each.

python · try it yourself
import random

MASK = (1 << 64) - 1
def mix64(x):
    x = (x + 0x9E3779B97F4A7C15) & MASK
    x = ((x ^ (x >> 30)) * 0xBF58476D1CE4E5B9) & MASK
    x = ((x ^ (x >> 27)) * 0x94D049BB133111EB) & MASK
    return x ^ (x >> 31)

class Cuckoo:
    """Cuckoo hashing (Pagh and Rodler): two tables of r slots; x lives in T[0][h0(x)] or T[1][h1(x)]."""
    def __init__(self, r, rng, max_kicks=None):
        self.r, self.rng = r, rng
        self.max_kicks = max_kicks or 6 * max(1, r.bit_length())
        self._new_functions()
        self.T = [[None] * r, [None] * r]
        self.n = self.kicks = self.rehashes = 0
    def _new_functions(self):
        self.seeds = (self.rng.getrandbits(64), self.rng.getrandbits(64))
    def _h(self, i, x):
        return mix64(x ^ self.seeds[i]) % self.r
    def contains(self, x):                          # at most 2 probes, worst case
        return self.T[0][self._h(0, x)] == x or self.T[1][self._h(1, x)] == x
    def insert(self, x):
        if self.contains(x): return True
        i = 0
        for _ in range(self.max_kicks):
            slot = self._h(i, x)
            x, self.T[i][slot] = self.T[i][slot], x  # put x here, pick up the previous occupant
            if x is None:
                self.n += 1; return True
            self.kicks += 1
            i = 1 - i                                # the evicted key goes to its other table
        return False                                 # probably a cycle: caller rehashes
    def rehash_insert(self, x):
        while not self.insert(x):                    # x is the key left homeless
            self.rehashes += 1
            keys = [k for t in self.T for k in t if k is not None] + [x]
            self._new_functions()
            self.T, self.n = [[None] * self.r, [None] * self.r], 0
            x = None
            for k in keys:
                if not self.insert(k):
                    x = k; break                     # failed again: rehash again
            if x is None: return

# The load threshold: fill tables with random keys until the first insertion fails (no rehashing).
rng = random.Random(7)
for r in [100, 1000, 10000]:
    loads = []
    for trial in range(5):
        c = Cuckoo(r, rng, max_kicks=500)
        while c.insert(rng.getrandbits(40)):
            pass
        loads.append(c.n / (2 * r))
    print(f"r = {r:5} slots per table: first failure at load " + ", ".join(f"{x:.3f}" for x in loads))
r =   100 slots per table: first failure at load 0.735, 0.600, 0.645, 0.645, 0.550
r =  1000 slots per table: first failure at load 0.536, 0.576, 0.538, 0.573, 0.565
r = 10000 slots per table: first failure at load 0.508, 0.515, 0.522, 0.521, 0.480

Small tables survive beyond load 1/21/2 by luck; as rr grows, the failure point concentrates near 1/21/2, the threshold of the random graph.

In C++

A cuckoo set with std::optional slots for a million slots in total, loaded to 0.45, with an explicit rehash loop for the rare failure.

cpp · try it yourself
#include <cstdint>
#include <cstdio>
#include <optional>
#include <random>
#include <utility>
#include <vector>

std::uint64_t mix64(std::uint64_t x) {
    x += 0x9E3779B97F4A7C15ULL;
    x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9ULL;
    x = (x ^ (x >> 27)) * 0x94D049BB133111EBULL;
    return x ^ (x >> 31);
}

class CuckooSet {
    std::size_t r;
    std::vector<std::optional<std::uint64_t>> T[2];
    std::uint64_t seed[2];
    std::mt19937_64& rng;
    std::size_t h(int i, std::uint64_t x) const { return mix64(x ^ seed[i]) % r; }
    bool try_insert(std::uint64_t x) {
        int i = 0;
        for (int step = 0; step < 200; ++step) {
            auto& slot = T[i][h(i, x)];
            if (!slot) { slot = x; return true; }
            std::swap(x, *slot);                      // evict the occupant, carry it on
            ++kicks;
            i = 1 - i;
        }
        pending = x;                                  // the key left without a slot
        return false;
    }
    void rehash() {
        ++rehashes;
        std::vector<std::uint64_t> keys{pending};
        for (auto& t : T) for (auto& s : t) if (s) keys.push_back(*s);
        for (;;) {
            seed[0] = rng(); seed[1] = rng();
            for (auto& t : T) t.assign(r, std::nullopt);
            bool ok = true;
            for (auto k : keys) if (!try_insert(k)) { ok = false; break; }
            if (ok) return;
            ++rehashes;
        }
    }
    std::uint64_t pending = 0;
public:
    long kicks = 0, rehashes = 0;
    CuckooSet(std::size_t slots_per_table, std::mt19937_64& g) : r(slots_per_table), rng(g) {
        seed[0] = rng(); seed[1] = rng();
        for (auto& t : T) t.assign(r, std::nullopt);
    }
    bool contains(std::uint64_t x) const { return T[0][h(0, x)] == x || T[1][h(1, x)] == x; }
    void insert(std::uint64_t x) { if (!contains(x) && !try_insert(x)) rehash(); }
};

int main() {
    std::mt19937_64 rng(2001);
    const std::size_t r = 500000;
    CuckooSet s(r, rng);
    std::vector<std::uint64_t> keys;
    for (std::size_t i = 0; i < 450000; ++i) keys.push_back(rng() >> 1);   // load 0.45 of 2r slots
    for (auto k : keys) s.insert(k);
    std::size_t found = 0, false_hits = 0;
    for (auto k : keys) found += s.contains(k);
    for (int i = 0; i < 100000; ++i) false_hits += s.contains((rng() >> 1) | (1ULL << 63));
    std::printf("%zu keys at load 0.45: %.3f evictions per insert, %ld rehashes\n",
                keys.size(), double(s.kicks) / keys.size(), s.rehashes);
    std::printf("found %zu of %zu, false hits %zu; every lookup reads 2 slots\n", found, keys.size(), false_hits);
}
450000 keys at load 0.45: 0.554 evictions per insert, 0 rehashes
found 450000 of 450000, false hits 0; every lookup reads 2 slots

Raising the load factor

A load below 50% wastes half the space. Two generalizations push the threshold up, at the cost of more probes per lookup, still O(1)O(1) worst case:

Variant Lookup probes (worst case) Load threshold
2 tables, 1 key per slot (Pagh and Rodler) 2 0.50.5
d=3d = 3 hash functions, 1 key per slot (Fotakis, Pagh, Sanders and Spirakis, 2005) 3 about 0.9180.918
d=4d = 4 hash functions 4 about 0.9770.977
2 hash functions, buckets of 4 slots (Dietzfelbinger and Weidling, 2007) 8 slots in 2 buckets about 0.980.98

The thresholds for d≥3d \ge 3 were determined exactly around 2009 to 2010 by several groups (Dietzfelbinger, Goerdt, Mitzenmacher, Montanari, Pagh and Rink; Fountoulakis and Panagiotou; Frieze and Melsted). A stash of a few extra slots (Kirsch, Mitzenmacher and Wieder, 2009) reduces the failure probability from O(1/n)O(1/n) to O(1/ns+1)O(1/n^{s+1}) with a stash of size ss. Bucketed cuckoo hashing is the basis of cuckoo filters (Fan et al. 2014), which replace Bloom filters when deletions are needed, and of many hardware and network lookup tables, because a lookup touches exactly two cache lines.

Test yourself

How many table slots does a cuckoo hashing lookup read in the worst case?

  1. 1
  2. 2
  3. O(lg⁡n)O(\lg n)
  4. O(lg⁡n/lg⁡lg⁡n)O(\lg n / \lg \lg n)

In the cuckoo graph, when can a set of keys be stored?

  1. When the graph is a tree
  2. When every connected component has at most one cycle
  3. When the graph is bipartite
  4. When no two keys share a slot under h0h_0

With two tables of rr slots each, which load keeps the expected insertion time O(1)O(1)?

  1. n≤2rn \le 2r
  2. n≤(1−ε)rn \le (1 - \varepsilon) r, a load below 1/21/2 of the 2r2r slots
  3. n≤rn \le \sqrt{r}
  4. Any load