Sub topic 8
Collisions: chaining and open addressing
This chapter assumes you know that a hash function turns a key into an integer, and that a table uses that integer to pick a slot in an array. Here you will see what happens when two different keys pick the same slot.
Why collisions are unavoidable
A table with 8 slots can hold many more than 8 possible keys, so some keys must share a slot. Two keys that land on the same slot are a collision. Even with a good hash function, collisions appear early. With 23 keys in a table of 365 slots, a collision is already more likely than not (the birthday effect). A table must handle collisions correctly, not try to prevent every one.
Two standard strategies exist: chaining and open addressing.
Chaining
With chaining, each slot holds a small collection of entries, called a bucket. This is usually a list. To insert, find the bucket from the hash and scan it for an equal key. If one exists, replace its value. If not, append a new entry. Lookup follows the same path. The ChainedMap from earlier in this tutorial works this way.
Chaining is simple. Deleting an entry just removes it from its bucket. The cost is extra memory for the bucket objects and poorer cache behavior, because entries are scattered across memory.
Open addressing
With open addressing, every entry lives directly in the array. If the slot is taken, the table probes for another one by following a fixed sequence. The simplest sequence is linear probing: try the next slot, then the next, wrapping at the end.
class ProbingSet:
def __init__(self, capacity=8):
self._slots = [None] * capacity
def add(self, key):
n = len(self._slots)
i = hash(key) % n
for _ in range(n):
if self._slots[i] is None:
self._slots[i] = key
return True
if self._slots[i] == key:
return False
i = (i + 1) % n
raise RuntimeError("table full")
def __contains__(self, key):
n = len(self._slots)
i = hash(key) % n
for _ in range(n):
if self._slots[i] is None:
return False
if self._slots[i] == key:
return True
i = (i + 1) % n
return False
s = ProbingSet(4)
for k in [1, 5, 9]: # all hash to slot 1 when the capacity is 4
s.add(k)
print(5 in s, 13 in s) # True FalseKeys 1, 5 and 9 all start at slot 1, so they end up in slots 1, 2 and 3. Looking up 13 also starts at slot 1. It probes past 1, 5 and 9 and stops at the empty slot 0. An empty slot proves the key is absent.
Deletion needs care
You cannot simply empty a slot when deleting. If 5 were removed from slot 2, a lookup for 9 would stop at the empty slot 2 and wrongly report that 9 is missing. Real implementations leave a marker, called a tombstone, that lookups skip over and inserts may reuse.
Comparing the two
| Aspect | Chaining | Open addressing |
|---|---|---|
| Storage | Array of buckets, plus entries | Entries stored in the array itself |
| Deletion | Remove from bucket | Needs tombstones |
| Cache behavior | Pointer chasing | Contiguous, usually faster |
| Behavior when crowded | Buckets grow longer | Probe runs grow, and the table can fill |
Python's built-in dict and set use open addressing. Java's HashMap uses chaining. Both give average constant-time operations as long as the table is not too crowded. The next chapter covers how resizing keeps it that way.
Exercise
In an open-addressing table with linear probing and capacity 4, keys 1, 5 and 9 sit in slots 1, 2 and 3. If key 5 is deleted by setting slot 2 back to empty, what goes wrong when you look up 9, and what fixes it?
Show answer
The lookup for 9 starts at slot 1, finds key 1, moves to slot 2, sees it is empty and concludes 9 is absent, although it sits in slot 3. Marking slot 2 with a tombstone fixes this. Lookups skip tombstones and keep probing, and inserts may reuse them.