Sub topic 14
Robin Hood hashing (extension)
This chapter assumes you know linear probing, primary clustering, and tombstones from the earlier chapters. Robin Hood hashing is a small change to linear probing. It keeps the table array and the probe order, and it changes which key gets to stay in a contested slot.
The idea: take from the rich
In plain linear probing, the key that arrives first keeps its slot. A later key may probe far from its home slot, and a few unlucky keys end up with long probe sequences.
Robin Hood hashing tracks each entry's probe distance. This is the number of slots between the entry's home slot and where it actually sits. During insertion, a "poor" entry (far from home) takes the slot of a "rich" entry (close to home). The rich entry is evicted and continues probing.
The total work stays about the same. The variance drops, because no key ends up with a very long probe sequence.
Insertion rule
While probing, compare your current distance d with the resident's distance. If the resident is closer to its own home than you are to yours, swap. Then keep probing with the evicted entry.
Implementation
This version has no resizing, to keep the code short. Add it the same way as in the chaining chapter.
class RobinHoodMap:
def __init__(self, capacity=8):
self._slots = [None] * capacity
self._size = 0
def _home(self, key):
return hash(key) % len(self._slots)
def _distance(self, key, index):
return (index - self._home(key)) % len(self._slots)
def _find(self, key):
n = len(self._slots)
i = self._home(key)
for dist in range(n):
slot = self._slots[i]
if slot is None or self._distance(slot[0], i) < dist:
return None # key would have displaced this resident
if slot[0] == key:
return i
i = (i + 1) % n
return None
def put(self, key, value):
idx = self._find(key)
if idx is not None:
self._slots[idx] = (key, value)
return
n = len(self._slots)
if self._size == n:
raise RuntimeError("table full")
entry = (key, value)
i = self._home(key)
dist = 0
while self._slots[i] is not None:
resident = self._slots[i]
resident_dist = self._distance(resident[0], i)
if resident_dist < dist:
self._slots[i], entry = entry, resident
dist = resident_dist
i = (i + 1) % n
dist += 1
self._slots[i] = entry
self._size += 1
def get(self, key, default=None):
idx = self._find(key)
return default if idx is None else self._slots[idx][1]
def remove(self, key):
i = self._find(key)
if i is None:
return False
n = len(self._slots)
for _ in range(n - 1): # backward-shift deletion
nxt = (i + 1) % n
slot = self._slots[nxt]
if slot is None or self._distance(slot[0], nxt) == 0:
break
self._slots[i] = slot
i = nxt
self._slots[i] = None
self._size -= 1
return True
m = RobinHoodMap()
m.put(3, "a")
m.put(4, "b")
m.put(11, "c") # home slot 3, same as key 3
print(m._slots)
m.remove(3)
print(m._slots)The first print shows [None, None, None, (3, 'a'), (11, 'c'), (4, 'b'), None, None]. Key 11 evicted key 4 because 4 was at distance 0 and 11 was already at distance 1. The second print shows [None, None, None, (11, 'c'), (4, 'b'), None, None, None].
Two payoffs
- Early exit on misses. Entries along a probe run are ordered by distance. If the resident at distance
dis closer to home than you, your key cannot be further along._findstops there instead of scanning to an empty slot. - Deletion without tombstones. Remove the entry, then shift each following entry back one slot until you reach an empty slot or an entry already at its home. The table ends up as if the key had never been inserted, so probe runs do not fill with tombstones.
Costs
- Each probe computes a home slot, which means rehashing the resident's key. Many implementations store the distance or the hash in the slot to avoid this.
- Insertion can move several entries, so it is slightly more expensive than plain linear probing.
Exercise
Why can _find return "not found" as soon as it meets a resident whose distance is less than the current dist, without reaching an empty slot?
Show answer
Insertion never leaves a closer-to-home entry ahead of a farther one in a probe run. If the key were in the table, it would have swapped into that slot or an earlier one. Meeting a resident with a smaller distance therefore proves the key is absent.