Sub topic 6
Linear probing
This chapter assumes you know arrays and indexing, basic Python classes and tuples, modulo arithmetic, and the idea of average versus worst-case cost. It also assumes you have read the previous chapter on open addressing.
The idea
Linear probing is the simplest open-addressing scheme. Every key lives in the table array itself. A key's home slot is hash(key) % capacity. If that slot is taken, you try the next slot, then the next, and wrap around to index 0 after the last slot.
The probe sequence for a key with home slot h in a table of size n is:
h, h+1, h+2, ... (all taken modulo n)An empty slot ends the search. This works only because insertion always uses the first free slot on the probe path. If the key were in the table, you would have reached it before hitting an empty slot.
Implementation
The code below uses two sentinel objects. _EMPTY marks a slot that was never used. _DELETED marks a tombstone, a slot whose key was removed. The next chapter covers tombstones in depth. For now, note that _find skips them while searching and remembers the first one as a spot for inserting.
_EMPTY = object()
_DELETED = object()
class LinearProbingMap:
def __init__(self, capacity=8):
self._slots = [_EMPTY] * capacity
self._live = 0
def _find(self, key):
"""Return (index of key or None, slot where key could be inserted)."""
n = len(self._slots)
start = hash(key) % n
first_free = None
for step in range(n):
i = (start + step) % n
slot = self._slots[i]
if slot is _EMPTY:
return None, (first_free if first_free is not None else i)
if slot is _DELETED:
if first_free is None:
first_free = i
elif slot[0] == key:
return i, first_free
return None, first_free
def put(self, key, value):
idx, free = self._find(key)
if idx is not None:
self._slots[idx] = (key, value)
return
if free is None:
raise RuntimeError("table full")
self._slots[free] = (key, value)
self._live += 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):
idx, _ = self._find(key)
if idx is None:
return False
self._slots[idx] = _DELETED
self._live -= 1
return True
m = LinearProbingMap()
m.put(3, "a")
m.put(11, "b")
m.put(19, "c")
print(m.get(19))
m.remove(11)
print(m.get(19))
m.put(27, "d")
print(m._slots[4])Small integers hash to themselves, so 3, 11, and 19 all have home slot 3 in a table of 8. They end up in slots 3, 4, and 5. The program prints c, then c again, then (27, 'd'). The second c shows why removal needs a tombstone. Without one, slot 4 would become empty and the lookup for 19 would stop there and wrongly report it missing. Key 27 reuses the tombstone at slot 4.
Common errors
- Stopping at a tombstone. A lookup must keep probing past
_DELETED. Only_EMPTYends the search. - Looping forever. Without the
range(n)bound, a table with no empty slots would never terminate. This class bounds the loop, but it also never resizes. - Forgetting to resize. This class raises
RuntimeError("table full")and never grows. A real table resizes well before it fills. - Overfilling. Probe chains lengthen quickly as the load factor approaches 1. Open addressing tables usually resize at a load factor of about 0.5 to 0.75.
Trade-offs
Linear probing scans neighboring slots, so it makes good use of the CPU cache. That is its main advantage over chaining. Its weakness is that occupied slots tend to merge into long runs. A new key whose home slot lands in a run must walk to the end of it and then extends the run. The next chapter covers this effect, called primary clustering.
Exercise
A table has capacity 8 and uses linear probing. You insert the integer keys 5, 13, 21, and then 6, in that order. In which slot does 6 end up, and how many slots does the insert examine?
Show answer
Keys 5, 13, and 21 all have home slot 5. They land in slots 5, 6, and 7. Key 6 has home slot 6, which is taken by 13. Slot 7 is taken by 21, so the probe wraps to slot 0, which is empty. Key 6 goes in slot 0, and the insert examines three slots: 6, 7, and 0.