Sub topic 4
Collision handling with open addressing
This chapter assumes you know what a collision is and have read the chaining chapter. You should be comfortable reading short Python programs and using Big-O notation.
Storing entries inside the array
Chaining keeps colliding entries in a list hanging off each bucket. Open addressing keeps every entry in the bucket array itself. Each slot holds at most one entry. If the slot you want is taken, you look at other slots in a fixed order until you find a free one.
The order of slots you examine is the probe sequence. The simplest version is linear probing: try index h, then h + 1, then h + 2, wrapping around at the end of the array.
Because every entry lives in the array, the table can never hold more entries than it has slots. The load factor (size divided by capacity) therefore cannot go above 1. Performance also drops sharply as it approaches 1, which later chapters quantify.
A working implementation
The table below stores (key, value) tuples. Two sentinel objects mark a slot as never used (_EMPTY) or previously used and then deleted (_DELETED). It has no resize logic yet, so it raises an error when full.
class LinearProbingTable:
_EMPTY = object()
_DELETED = object()
def __init__(self, capacity=8):
self._slots = [self._EMPTY] * capacity
def _probe(self, key):
n = len(self._slots)
start = hash(key) % n
for step in range(n):
yield (start + step) % n
def put(self, key, value):
first_free = None
for i in self._probe(key):
slot = self._slots[i]
if slot is self._EMPTY:
if first_free is None:
first_free = i
break
if slot is self._DELETED:
if first_free is None:
first_free = i
elif slot[0] == key:
self._slots[i] = (key, value)
return
if first_free is None:
raise RuntimeError("table is full")
self._slots[first_free] = (key, value)
def get(self, key, default=None):
for i in self._probe(key):
slot = self._slots[i]
if slot is self._EMPTY:
return default
if slot is not self._DELETED and slot[0] == key:
return slot[1]
return default
def delete(self, key):
for i in self._probe(key):
slot = self._slots[i]
if slot is self._EMPTY:
return False
if slot is not self._DELETED and slot[0] == key:
self._slots[i] = self._DELETED
return True
return False
table = LinearProbingTable(8)
for k in (1, 9, 17): # all hash to index 1 when capacity is 8
table.put(k, f"value-{k}")
table.delete(9)
print(table.get(17)) # value-17
print(table.get(9)) # NonePython hashes small integers to themselves, so keys 1, 9, and 17 all start at index 1. They end up in slots 1, 2, and 3.
Why deletion needs a marker
Suppose delete(9) simply set slot 2 back to empty. A later get(17) would start at slot 1, see a mismatch, reach the now-empty slot 2, and stop. It would report "not found" even though 17 sits in slot 3.
A lookup is allowed to stop only at a slot that was never used. A deleted slot gets a tombstone marker instead. Lookups skip over tombstones, and inserts may reuse them, but only after the search has confirmed the key is not already present further along. That is why put remembers first_free and keeps scanning.
Clustering and other probe sequences
Linear probing has a weakness called primary clustering. Occupied slots form runs. Any key hashing into a run extends it, so long runs grow longer. Probing is cache-friendly, which is the main reason people still use it.
Two alternatives spread entries out more:
| Scheme | Next slot after the `i`-th collision | Trade-off |
|---|---|---|
| Linear probing | `h + i` | Fast, cache-friendly, forms clusters |
| Quadratic probing | `h + i²` | Fewer clusters, may not reach every slot unless capacity is chosen carefully |
| Double hashing | `h1 + i * h2` | Least clustering, needs a second hash and a nonzero `h2` |
Chaining compared with open addressing
- Chaining tolerates a load factor above 1. Open addressing cannot.
- Open addressing avoids allocating a node per entry, which saves memory and pointer chasing.
- Deletion is simple with chaining. With open addressing it needs tombstones.
Exercise
A linear probing table has capacity 8. Keys 3, 11, and 19 are inserted in that order, and all hash to index 3. Key 11 is then deleted by setting its slot to empty instead of a tombstone. What does get(19) return, and why?
Show answer
It returns the default (not found). Keys 3, 11, and 19 occupy slots 3, 4, and 5. After 11's slot is set to empty, the lookup for 19 starts at slot 3, sees key 3, reaches empty slot 4, and stops. It never reaches slot 5. A tombstone would have told the lookup to keep going.