Sub topic 11
Open Addressing, Tombstones and Rebuilds
This chapter assumes you know big-O notation, how a chained hash table works, and the load factor from the earlier chapters. Here you will see how amortised analysis carries over to open addressing, and why deletions force a second kind of rebuild.
Open addressing in brief
A chained table stores colliding keys in a list per bucket. An open-addressing table stores every entry directly in one flat array. When a key's home slot is taken, the table probes: it checks another slot, then another, following a fixed rule until it finds a free one. Linear probing, the simplest rule, tries the next slot each time.
The load factor is still size / capacity, but it can never exceed 1, because each slot holds one entry. Probe sequences also get long as the table fills. With linear probing, the expected number of probes for an insert grows roughly like 1 / (1 − α)², where α is the load factor. So open addressing needs a lower maximum load than chaining. Many implementations resize at about 0.5 to 0.7.
The resize argument is the same as in the chained case. When the load passes the limit, allocate a table of double the capacity and reinsert every entry. That costs O(n) once, but it happens after a number of inserts proportional to n, so insertion is amortised O(1) (expected, given a good hash function).
Why deletion is a problem
Suppose you delete a key by emptying its slot. Lookups stop at the first empty slot, because an empty slot means "the key was never placed past here". Emptying a slot in the middle of a probe chain breaks that rule, and keys stored after it become unreachable.
The standard fix is a tombstone. Deleting a key replaces it with a special marker meaning "something was here". Lookups treat a tombstone as occupied and keep probing. Inserts may reuse a tombstone slot, once the key is known to be absent from the rest of the chain.
A table with tombstones
EMPTY = object()
TOMBSTONE = object()
class OpenAddressTable:
MAX_LOAD = 0.5
def __init__(self):
self._slots = [EMPTY] * 8
self._live = 0
self._used = 0 # live entries plus tombstones rebuild_count = 0
self.rebuilds = 0
def _find(self, key):
"""Return (index of key or None, index of first reusable slot)."""
cap = len(self._slots)
i = hash(key) % cap
reusable = None
for _ in range(cap):
slot = self._slots[i]
if slot is EMPTY:
return None, reusable if reusable is not None else i
if slot is TOMBSTONE:
if reusable is None:
reusable = i
elif slot[0] == key:
return i, reusable
i = (i + 1) % cap
return None, reusable
def put(self, key, value):
found, free = self._find(key)
if found is not None:
self._slots[found] = (key, value)
return
if self._slots[free] is EMPTY:
self._used += 1
self._slots[free] = (key, value)
self._live += 1
if self._used > self.MAX_LOAD * len(self._slots):
self._rebuild()
def get(self, key, default=None):
found, _ = self._find(key)
return default if found is None else self._slots[found][1]
def delete(self, key):
found, _ = self._find(key)
if found is None:
return False
self._slots[found] = TOMBSTONE
self._live -= 1
return True
def _rebuild(self):
entries = [s for s in self._slots if s is not EMPTY and s is not TOMBSTONE]
# Grow only if live entries need it; otherwise rebuild at the same size.
cap = len(self._slots)
if self._live > self.MAX_LOAD * cap / 2:
cap *= 2
self._slots = [EMPTY] * cap
self._live = self._used = 0
self.rebuilds += 1
for k, v in entries:
self.put(k, v)
table = OpenAddressTable()
for i in range(1000):
table.put(i, i)
if i % 2 == 0:
table.delete(i)
assert table.get(1) == 1 and table.get(2) is None
print(table.rebuilds, len(table._slots))The counter _used includes tombstones, and the rebuild trigger uses it. Probe length depends on how many slots are non-empty, not on how many entries are live. A table full of tombstones is as slow as a full table.
Rebuilds and the amortised bound
A rebuild scans the whole array and reinserts the live entries, costing O(capacity). It is triggered only after enough inserts have raised _used to the limit. After a rebuild, _used equals _live, which is at most a quarter of the capacity when the table does not grow, or lower when it does. The next rebuild therefore needs at least a constant fraction of the capacity in new insertions. Charging the rebuild cost to those insertions gives O(1) amortised per insert, the same accounting argument used for the dynamic array.
Deletions are cheap (O(1) expected) and need no extra charge. They only add tombstones, which the next rebuild clears.
Common errors
- Clearing a slot on delete instead of placing a tombstone.
- Counting only live entries when deciding to rebuild, which lets tombstones degrade probing without bound.
- Stopping a lookup at a tombstone. Only an empty slot ends the search.
Exercise
A table with capacity 16 and a maximum load of 0.5 holds 3 live entries and 5 tombstones. The next insert of a new key finds no reusable tombstone on its probe path. Does this insert trigger a rebuild, and does the rebuild grow the table?
Show answer
The non-empty count is 8 before the insert and 9 after it, which exceeds 0.5 × 16 = 8, so a rebuild triggers. Live entries after the insert are 4. The table grows only if live entries exceed 0.5 × 16 / 2 = 4, and 4 is not greater than 4, so it rebuilds at capacity 16 and clears the tombstones.