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. You should be comfortable with a probe sequence, the idea of a home slot, and why long probe runs hurt lookup time.
Plain linear probing and chaining are the baseline designs. Robin Hood and cuckoo hashing are two refinements that change the placement rules to cut worst-case lookup cost. Robin Hood evens out probe lengths within an open-addressing table. Cuckoo hashing gives every key exactly two possible locations, so a lookup is at most two reads.
The problem with plain linear probing
In linear probing, the first key to arrive claims its home slot. Later keys that hash nearby are pushed along the array. Some keys end up far from home, and a lookup for one of those keys is slow. The average probe count can look fine while a few unlucky keys pay for it, and the variance in probe length grows quickly as the table fills.
Define the probe distance (also called displacement) of an entry as the number of slots between its home slot and the slot where it actually sits. Robin Hood hashing tries to keep the largest probe distance small, not only the average.
Robin Hood hashing
Robin Hood hashing is linear probing with one extra rule on insert. While probing, compare the incoming entry's current distance with the distance of the resident in the slot. If the incoming entry has traveled farther, it takes the slot ("steals from the rich"), and the evicted resident continues probing from there.
Here is a worked trace in a table of 8 slots. Slot 2 holds A (home 2, distance 0). Slot 3 holds B (home 2, distance 1). Slot 4 holds C (home 3, distance 1). Now insert D, whose home is slot 2.
- At slot 2, D has distance 0 and A has distance 0. D has not traveled farther, so D moves on.
- At slot 3, D has distance 1 and B has distance 1. D moves on.
- At slot 4, D has distance 2 and C has distance 1. D has traveled farther, so D takes slot 4 and C continues.
- C moves to slot 5 with distance 2.
The result has a maximum distance of 2. Plain linear probing would have put D at slot 5 with distance 3.
This ordering also makes unsuccessful lookups faster. Within a run of entries, distances never drop below what position implies. So a lookup can stop as soon as it meets a resident whose distance is smaller than its own current distance. The key cannot be further along, because Robin Hood insertion would have placed it before that resident.
Implementation
Each slot stores (key, value, distance). Deletion uses a backward shift instead of tombstones: after removing an entry, pull each following entry one slot back until you reach an empty slot or an entry already at its home. This keeps the table free of tombstones and keeps the stop-early rule valid.
class RobinHoodTable:
def __init__(self, capacity=8, max_load=0.8):
self._slots = [None] * capacity
self._size = 0
self._max_load = max_load
def __len__(self):
return self._size
def _insert(self, key, value):
n = len(self._slots)
i = hash(key) % n
entry = (key, value, 0)
while True:
slot = self._slots[i]
if slot is None:
self._slots[i] = entry
self._size += 1
return
if slot[0] == entry[0]:
# Update in place. The key can only be found before any swap.
self._slots[i] = (entry[0], entry[1], slot[2])
return
if slot[2] < entry[2]:
self._slots[i], entry = entry, slot
i = (i + 1) % n
entry = (entry[0], entry[1], entry[2] + 1)
def put(self, key, value):
if (self._size + 1) / len(self._slots) > self._max_load:
self._resize(len(self._slots) * 2)
self._insert(key, value)
def get(self, key, default=None):
n = len(self._slots)
i = hash(key) % n
dist = 0
while True:
slot = self._slots[i]
if slot is None or slot[2] < dist:
return default
if slot[0] == key:
return slot[1]
i = (i + 1) % n
dist += 1
def remove(self, key):
n = len(self._slots)
i = hash(key) % n
dist = 0
while True:
slot = self._slots[i]
if slot is None or slot[2] < dist:
return False
if slot[0] == key:
break
i = (i + 1) % n
dist += 1
nxt = (i + 1) % n
while self._slots[nxt] is not None and self._slots[nxt][2] > 0:
k, v, d = self._slots[nxt]
self._slots[i] = (k, v, d - 1)
i = nxt
nxt = (nxt + 1) % n
self._slots[i] = None
self._size -= 1
return True
def _resize(self, new_capacity):
old = self._slots
self._slots = [None] * new_capacity
self._size = 0
for slot in old:
if slot is not None:
self._insert(slot[0], slot[1])
t = RobinHoodTable()
for k in range(0, 80, 8): # integer keys that collide heavily
t.put(k, k)
print(t.get(24))
print(t.remove(24), t.get(24))
print(t.get(32), len(t))The loop in get terminates because put keeps the load factor below 1, so at least one slot is always empty.
Trade-offs
- Lookups, especially misses, have lower variance, and the table tolerates a higher load factor (often 0.8 to 0.9) than plain linear probing.
- Inserts do more work, because they may move several entries. Each entry also stores its distance, or you recompute it from the hash.
- Backward-shift deletion touches several slots, but it avoids the tombstone buildup described in the earlier chapter.
- Probing is still sequential, so it keeps the cache-friendly access pattern of linear probing.
Cuckoo hashing
Cuckoo hashing takes a different approach. It uses two hash functions, and every key may live only at h1(key) in table 0 or at h2(key) in table 1. A lookup reads at most two slots. That gives a worst-case lookup of O(1), not just an average one.
Insertion is where the work happens. Put the new entry in its table-0 slot. If that slot was occupied, the old resident is evicted ("kicked out", like a cuckoo chick) and must move to its other location in the other table. That may evict another entry, and so on.
Eviction chains can loop forever: two entries might need each other's slots. So the insert counts kicks and gives up after a limit, commonly about log n. On failure, the table picks new hash functions, usually grows, and reinserts everything.
Implementation
This version seeds its two hash functions with random values, so a rebuild changes both.
import random
class CuckooHashTable:
def __init__(self, capacity=8, max_kicks=32):
self._cap = capacity
self._tables = [[None] * capacity, [None] * capacity]
self._seeds = [random.random(), random.random()]
self._max_kicks = max_kicks
self._size = 0
def __len__(self):
return self._size
def _index(self, which, key):
return hash((self._seeds[which], key)) % self._cap
def get(self, key, default=None):
for w in (0, 1):
slot = self._tables[w][self._index(w, key)]
if slot is not None and slot[0] == key:
return slot[1]
return default
def _place(self, entry):
"""Try to place entry. Return None on success, else the homeless entry."""
w = 0
for _ in range(self._max_kicks):
i = self._index(w, entry[0])
entry, self._tables[w][i] = self._tables[w][i], entry
if entry is None:
return None
w = 1 - w
return entry
def put(self, key, value):
for w in (0, 1):
i = self._index(w, key)
slot = self._tables[w][i]
if slot is not None and slot[0] == key:
self._tables[w][i] = (key, value)
return
homeless = self._place((key, value))
self._size += 1
if homeless is not None:
self._grow(homeless)
def _grow(self, extra):
items = [s for t in self._tables for s in t if s is not None]
items.append(extra)
self._cap *= 2
while True:
self._tables = [[None] * self._cap, [None] * self._cap]
self._seeds = [random.random(), random.random()]
if all(self._place(e) is None for e in items):
return
def remove(self, key):
for w in (0, 1):
i = self._index(w, key)
slot = self._tables[w][i]
if slot is not None and slot[0] == key:
self._tables[w][i] = None
self._size -= 1
return True
return False
c = CuckooHashTable()
for i in range(100):
c.put(f"k{i}", i)
print(c.get("k42"), c.get("missing"), len(c))
print(c.remove("k42"), c.get("k42"))Note that _place returns the evicted entry when the kick limit is hit. The caller must keep that entry, or it would be lost. _grow rebuilds from a separate list of items, so a failed attempt can be retried with fresh seeds without losing data.
Trade-offs
- Lookups and deletions are O(1) worst case, and deletion needs no tombstones.
- Inserts are O(1) on average but can trigger a full rebuild, which costs O(n).
- Load factor is limited. With two tables and one entry per slot, inserts start failing often once the table is about 50% full. Variants with more hash functions or several entries per bucket reach higher loads.
- Each lookup may touch two unrelated cache lines, so it is not always faster than a short linear probe in practice.
- The hash functions must behave independently. Weak hash functions cause frequent rebuilds.
Choosing a scheme
| Scheme | Lookup cost | Typical max load | Deletion | Main weakness |
|---|---|---|---|---|
| Chaining | Average O(1), long chains possible | 0.75 to 1.0 or higher | Remove from list | Pointer overhead, poor cache use |
| Linear probing | Average O(1), long clusters | 0.5 to 0.7 | Tombstones | Primary clustering |
| Robin Hood | Average O(1), low variance | 0.8 to 0.9 | Backward shift | Costlier inserts |
| Cuckoo | Worst-case O(1) (2 reads) | About 0.5 (two tables) | Clear the slot | Insert failures, rebuilds |
Exercise
In the Robin Hood table, slot 5 holds P (home 5, distance 0), slot 6 holds Q (home 5, distance 1), and slot 7 is empty. You insert R with home slot 5. Where does each of P, Q, and R end up, and what are their distances?
Show answer
At slot 5, R (distance 0) does not beat P (distance 0), so R moves on. At slot 6, R has distance 1 and Q has distance 1, so R moves on. At slot 7 the slot is empty, so R lands there with distance 2. P stays at slot 5 (distance 0), Q stays at slot 6 (distance 1), and R sits at slot 7 (distance 2). No swap happens because R never travels farther than a resident.
Exercise
Why does a cuckoo insert need a kick limit, and what must the insert do when the limit is reached?
Show answer
Eviction chains can cycle, for example when two entries each need the other's slot, so an unbounded loop might never end. When the limit is reached, the insert holds one homeless entry. It must keep that entry, pick new hash functions (usually with larger tables), and reinsert every entry including the homeless one.