Sub topic 15
Robin Hood and cuckoo hashing
This chapter assumes you have read the earlier chapters on linear probing, tombstones, load factor, and resizing. Both schemes below change how an open-addressing table places entries, to make lookups more predictable.
Robin Hood hashing
Robin Hood hashing is linear probing with one extra rule. Each entry records its probe distance, which is how far it sits from its home slot (the slot its hash points to). When an insert probes past an entry that is closer to home than the new entry, the new entry takes that slot. The displaced entry continues probing from there.
The rule takes from the "rich" (entries near home) and gives to the "poor" (entries far from home). The effects are:
- Probe distances become more even, so the longest probe sequence is shorter.
- A lookup can stop early. If the probe reaches a slot whose entry is closer to home than the lookup's own distance, the key is not in the table.
- Deletion can use backward shifting instead of tombstones. Later entries move one slot back until you reach an empty slot or an entry already at home.
The cost is extra bookkeeping on insert and a stored distance per entry.
Cuckoo hashing
Cuckoo hashing uses two hash functions and two tables. A key may live only in table[0][h0(key)] or table[1][h1(key)]. A lookup therefore checks at most two slots, so the worst-case lookup is O(1).
Insertion places the key in its first slot. If that slot is occupied, the new key evicts the old one, and the evicted key moves to its alternative slot. This repeats until a key lands in an empty slot. If the chain runs too long, it has probably entered a cycle. The table then grows, or picks new hash functions, and reinserts everything.
class CuckooHashTable:
def __init__(self, capacity=8, max_kicks=16):
self._cap = capacity
self._t = [[None] * capacity, [None] * capacity]
self._max_kicks = max_kicks
def _idx(self, which, key):
h = hash(key) if which == 0 else hash((key, "salt"))
return h % self._cap
def get(self, key, default=None):
for w in (0, 1):
slot = self._t[w][self._idx(w, key)]
if slot is not None and slot[0] == key:
return slot[1]
return default
def put(self, key, value):
for w in (0, 1):
i = self._idx(w, key)
slot = self._t[w][i]
if slot is not None and slot[0] == key:
self._t[w][i] = (key, value)
return
item, w = (key, value), 0
for _ in range(self._max_kicks):
i = self._idx(w, item[0])
item, self._t[w][i] = self._t[w][i], item
if item is None:
return
w = 1 - w
self._rebuild(self._cap * 2, item)
def _rebuild(self, new_cap, extra):
items = [s for t in self._t for s in t if s is not None]
items.append(extra)
self._cap = new_cap
self._t = [[None] * new_cap, [None] * new_cap]
for k, v in items:
self.put(k, v)
t = CuckooHashTable()
for i in range(20):
t.put(i, i * i)
print(t.get(7), t.get(99))This prints 49 None. When the kick loop gives up, item is the one entry that has no home. Every other entry is still in a table, so _rebuild loses nothing.
Choosing between schemes
| Scheme | Lookup cost | Main strength | Main cost |
|---|---|---|---|
| Linear probing | Grows quickly with load | Simple, cache friendly | Long clusters |
| Robin Hood | Low variance, early exit | Even probe lengths, no tombstones | Distance bookkeeping |
| Cuckoo | At most 2 slots | Bounded worst-case lookup | Low load limit, rebuilds |
| Chaining | Chain length | Easy deletion | Pointer overhead |
Pick Robin Hood when you want open addressing with predictable lookups. Pick cuckoo when lookups must have a hard bound and you can pay in memory.
Exercise
In the cuckoo table above, why does a lookup never need to probe more than two slots, and what happens when an insert's eviction chain exceeds max_kicks?
Show answer
Each key can only be stored at its slot in table 0 or its slot in table 1, so get checks exactly those two slots. When the chain exceeds max_kicks, the table assumes a cycle, doubles its capacity, and reinserts every entry, including the one left without a slot.