Sub topic 7
Resolving collisions with linear probing
This chapter assumes you know how a hash function maps a key to a bucket index with the modulo operator. It also assumes you know what a collision is, and that you can read basic Python classes and loops.
The idea
Separate chaining resolves a collision by storing a list in each bucket. Open addressing keeps every entry directly in the slot array instead. When the home slot (the slot at hash(key) % size) is taken, the table tries other slots in a fixed order. This is called probing.
Linear probing is the simplest order. It checks the home slot, then the next slot, then the next, and wraps around to index 0 at the end of the array.
index = (hash(key) + attempt) % size for attempt = 0, 1, 2, ...Lookup follows the same path as insertion
A lookup must retrace the probe sequence that the insert used. It stops in one of two ways:
- It finds a slot whose key equals the search key. The lookup returns that value.
- It finds an empty slot. The key cannot be further along, because an insert would have used that empty slot. The lookup reports a miss.
A working implementation
This version supports insert, update, and lookup. It has a fixed capacity and raises an error when full. Resizing and deletion are covered in later chapters.
class LinearProbingTable:
def __init__(self, capacity=8):
self._slots = [None] * capacity
self._count = 0
def _probe(self, key):
n = len(self._slots)
i = hash(key) % n
for _ in range(n):
yield i
i = (i + 1) % n
def put(self, key, value):
for i in self._probe(key):
slot = self._slots[i]
if slot is None:
self._slots[i] = (key, value)
self._count += 1
return
if slot[0] == key:
self._slots[i] = (key, value)
return
raise RuntimeError("table is full")
def get(self, key, default=None):
for i in self._probe(key):
slot = self._slots[i]
if slot is None:
return default
if slot[0] == key:
return slot[1]
return default
t = LinearProbingTable()
t.put(3, "a")
t.put(11, "b") # 11 % 8 == 3, collides with key 3
t.put(19, "c") # 19 % 8 == 3, collides again
print(t._slots)
print(t.get(19), t.get(27))In CPython, small integers hash to themselves. Keys 3, 11, and 19 therefore all have home slot 3. They end up in slots 3, 4, and 5, and the output is:
[None, None, None, (3, 'a'), (11, 'b'), (19, 'c'), None, None]
c NoneThe lookup for 27 also starts at slot 3. It checks slots 3, 4, and 5, then reaches the empty slot 6 and returns None.
Clustering
Linear probing has a weakness called primary clustering. Occupied slots form contiguous runs. A key whose home slot lies inside a run joins the end of that run, which makes the run longer. Longer runs are more likely to be hit again, so probe sequences grow quickly as the table fills.
Cache behavior is the compensation. Neighboring slots sit next to each other in memory, so probing is fast per step. Open addressing needs a lower load factor than chaining to stay fast. A common maximum is about 0.5 to 0.7.
Common errors
- Looping forever on a full table. A probe loop with no step limit never ends when no slot is empty. Bound the loop to
nsteps, as_probedoes. - Forgetting wraparound. Without
% n, the index runs off the end of the array. - Stopping early after a removal. Setting a slot back to
Nonecan break the probe path for keys stored after it. The next chapter fixes this with tombstones.
Exercise
A table has 8 slots. Integer keys 5, 13, and 21 are inserted in that order, then 6 is inserted. Assuming hash(k) == k, which slot does each key occupy?
Show answer
Every one of 5, 13, and 21 has home slot 5 (5 % 8, 13 % 8, 21 % 8). They fill slots 5, 6, and 7. Key 6 has home slot 6, which is taken, so it probes slot 7 (taken), then wraps to slot 0 and is stored there.