Sub topic 7
Resolving collisions with linear probing
This chapter assumes you know how a hash function and a modulo turn a key into a bucket index, and that you know what a collision is. You should also be comfortable with Python lists and with introductory Big-O notation.
The idea: keep everything in one array
Separate chaining gives every bucket its own list. Open addressing takes a different route. The table is a single flat array of slots, and each slot holds at most one entry. When a key's home slot is already taken, the table looks for another slot in the same array.
Linear probing is the simplest version of that search. Start at hash(key) % n. If the slot is taken, try the next slot, then the one after it. When you run off the end of the array, wrap around to index 0. The sequence of slots you examine is the probe sequence:
i, i + 1, i + 2, ... (all taken modulo n)The same probe sequence is used for inserting, finding, and deleting. That sharing is what makes the scheme correct.
A worked trace
Take a table with 8 slots and use integer keys, where hash(k) == k in Python for small integers. The keys 3, 11, and 19 all have the home slot 3, because each leaves remainder 3 when divided by 8. The key 4 has home slot 4.
n = 8
slots = [None] * n
for key in [3, 11, 19, 4]:
i = key % n
while slots[i] is not None:
i = (i + 1) % n
slots[i] = key
print(slots)The program prints [None, None, None, 3, 11, 19, 4, None]. Here is how each key landed:
- Key 3 took its home slot 3.
- Key 11 found slot 3 taken and moved to slot 4.
- Key 19 found slots 3 and 4 taken and moved to slot 5.
- Key 4 had home slot 4. Slots 4 and 5 were taken, so it ended in slot 6, even though it never collided with 3, 11, or 19 in the hash sense.
The last step is the cost of linear probing. Entries with different home slots now compete for the same stretch of the array.
Lookup and the stop rule
To find a key, begin at its home slot and follow the same probe sequence. Stop when you find the key or when you reach an empty slot.
The empty slot is a valid stopping point because of an invariant: if the key were in the table, insertion would have placed it at the first free slot on its probe sequence. Every slot before that point was occupied at insertion time. So an empty slot on the path proves the key was never inserted.
That argument only holds if occupied slots never become empty again. This is why deletion needs special care, which the next chapter covers. The implementation below already uses a marker called a tombstone, so you will see it in the code.
A complete implementation
_EMPTY = object()
_DELETED = object()
class ProbingHashTable:
def __init__(self, capacity=8, max_load=0.5):
self._slots = [_EMPTY] * capacity
self._used = 0 # live entries plus tombstones
self._live = 0 # live entries only
self._max_load = max_load
def _find_slot(self, key):
n = len(self._slots)
i = hash(key) % n
for _ in range(n):
slot = self._slots[i]
if slot is _EMPTY:
return None
if slot is not _DELETED and slot[0] == key:
return i
i = (i + 1) % n
return None
def get(self, key, default=None):
i = self._find_slot(key)
return default if i is None else self._slots[i][1]
def put(self, key, value):
i = self._find_slot(key)
if i is not None:
self._slots[i] = (key, value)
return
if (self._used + 1) / len(self._slots) > self._max_load:
self._resize(len(self._slots) * 2)
n = len(self._slots)
i = hash(key) % n
while self._slots[i] is not _EMPTY and self._slots[i] is not _DELETED:
i = (i + 1) % n
if self._slots[i] is _EMPTY:
self._used += 1
self._slots[i] = (key, value)
self._live += 1
def remove(self, key):
i = self._find_slot(key)
if i is None:
return False
self._slots[i] = _DELETED
self._live -= 1
return True
def _resize(self, new_capacity):
old = self._slots
self._slots = [_EMPTY] * new_capacity
self._used = 0
self._live = 0
for slot in old:
if slot is not _EMPTY and slot is not _DELETED:
self.put(slot[0], slot[1])
t = ProbingHashTable()
for i in range(10):
t.put(i, i * i)
t.remove(3)
print(t.get(3), t.get(4))This prints None 16. A few design points are worth studying.
- Two sentinels.
_EMPTYand_DELETEDare uniqueobject()instances compared withis. A stored entry is always a(key, value)tuple, so a sentinel can never be confused with real data, even if a user storesNoneas a value. - Update before insert.
putcalls_find_slotfirst. If the key already exists, it overwrites in place. Without this step, the same key could appear twice along one probe sequence. - The
n-step loop._find_slotvisits at mostnslots. This guarantees termination even if the array had no_EMPTYslot left, which the load limit is designed to prevent. - Reusing tombstones. An insert may place a new entry in the first
_DELETEDslot it meets. Only taking over an_EMPTYslot increases_used. - Resizing rebuilds.
_resizere-inserts every live entry withput. Home slots depend onn, so entries cannot be copied across by position. Rebuilding also discards all tombstones.
Clustering and why the load limit is low
Linear probing has a known weakness called primary clustering. In the trace above, slots 3 to 6 formed a run of occupied slots. Any key whose home slot lands anywhere in that run joins it, and the run grows. A longer run is a larger target for the next key, so clusters grow faster as they get bigger.
Clustering is the reason the example table resizes at a load factor of 0.5, while a chained table can tolerate 0.75 or more. Under the standard analysis with a uniform hash function, the expected number of probes at load factor α is approximately:
- Successful lookup: ½ · (1 + 1 / (1 − α))
- Unsuccessful lookup: ½ · (1 + 1 / (1 − α)²)
| Load factor α | Probes, found | Probes, not found |
|---|---|---|
| 0.50 | 1.5 | 2.5 |
| 0.75 | 2.5 | 8.5 |
| 0.90 | 5.5 | 50.5 |
An unsuccessful search must walk to the end of a cluster, so it is hit hardest as the table fills. Because insertion also ends at a free slot, inserts cost about the same as unsuccessful searches. The low threshold keeps those costs at a few probes.
Strengths and trade-offs
Linear probing is popular in practice for one main reason. Adjacent slots sit next to each other in memory, so a probe sequence usually reads one or two cache lines. Chained tables chase a pointer for every list node, and each pointer can cost a cache miss. For small keys and values, this often makes linear probing faster than chaining despite needing more probes.
The costs are:
- Sensitivity to the hash function. A weak hash that maps many keys to nearby home slots creates large clusters. A table whose hash is
key % nand whose keys are all multiples of 8 would pile every key into a few slots. - Lower maximum load. The table must stay well under full, so it uses more memory per entry than a chained table at a high load factor.
- Awkward deletion. Entries cannot simply be erased, as the next chapter explains.
- No overflow. A chained table can exceed a load factor of 1. A probing table holds at most
nentries and must resize before that.
Exercise
A table has 8 slots, all empty, and uses linear probing with hash(k) = k. You insert the keys 5, 13, 6, and 21 in that order. Which slot does each key end up in?
Show answer
Key 5 goes to slot 5 (its home slot). Key 13 has home slot 5, which is taken, so it goes to slot 6. Key 6 has home slot 6, which is now taken, so it goes to slot 7. Key 21 has home slot 5. Slots 5, 6, and 7 are taken, so the probe wraps around to slot 0, and 21 lands there.
Exercise
Using the table from the previous exercise, you look up the key 29, whose home slot is 5. How many slots does the lookup examine before concluding the key is absent, and why is it safe to stop there?
Show answer
It examines slots 5, 6, 7, 0, and 1, which is five slots. Slots 5, 6, 7, and 0 hold other keys. Slot 1 is empty, so the lookup stops. This is safe because any key whose probe sequence passes through slot 1 would have been placed in slot 1 at insertion time, since it was free. Its being empty proves 29 was never inserted.