Sub topic 10
Deleting keys with tombstones
This chapter assumes you know linear probing from the previous chapter, including how a lookup walks forward from the home slot. It also assumes you can read basic Python classes and tuples.
Why simply emptying a slot fails
In open addressing, a lookup stops at the first empty slot. It reads an empty slot as meaning that the key was never inserted. Deleting a key by setting its slot back to empty breaks that rule.
Suppose keys 3, 11, and 19 all have home slot 3 in a table with 8 slots. They land in slots 3, 4, and 5. If you empty slot 4 after removing 11, a lookup for 19 starts at slot 3, then reaches the empty slot 4 and stops. It reports that 19 is missing, but 19 is still in slot 5.
The tombstone fix
A tombstone is a special marker that means "a key used to live here". It differs from an empty slot in two ways:
- A lookup treats a tombstone as occupied by a different key and keeps probing.
- An insert may reuse a tombstone, but only after the probe has confirmed that the key is not already further along the chain.
Each slot therefore has three states.
Implementation
The _find method in this class does the work. It remembers the first tombstone it passes, so put can reuse that slot. It still scans to the end of the chain first, in case the key is already stored.
_EMPTY = object()
_DELETED = object()
class LinearProbingMap:
def __init__(self, capacity=8):
self._slots = [_EMPTY] * capacity
self._live = 0
def _find(self, key):
"""Return (index of key or None, slot where key could be inserted)."""
n = len(self._slots)
start = hash(key) % n
first_free = None
for step in range(n):
i = (start + step) % n
slot = self._slots[i]
if slot is _EMPTY:
return None, (first_free if first_free is not None else i)
if slot is _DELETED:
if first_free is None:
first_free = i
elif slot[0] == key:
return i, first_free
return None, first_free
def put(self, key, value):
idx, free = self._find(key)
if idx is not None:
self._slots[idx] = (key, value)
return
if free is None:
raise RuntimeError("table full")
self._slots[free] = (key, value)
self._live += 1
def get(self, key, default=None):
idx, _ = self._find(key)
return default if idx is None else self._slots[idx][1]
def remove(self, key):
idx, _ = self._find(key)
if idx is None:
return False
self._slots[idx] = _DELETED
self._live -= 1
return True
class NaiveDeleteMap(LinearProbingMap):
def remove(self, key):
idx, _ = self._find(key)
if idx is None:
return False
self._slots[idx] = _EMPTY # wrong: cuts the probe chain
self._live -= 1
return True
for cls in (NaiveDeleteMap, LinearProbingMap):
m = cls()
for k, v in [(3, "a"), (11, "b"), (19, "c")]:
m.put(k, v)
m.remove(11)
print(cls.__name__, m.get(19))
m.put(27, "d")
print(m._slots[4]) # the tombstone at slot 4 was reusedThe program prints NaiveDeleteMap None, then LinearProbingMap c, then (27, 'd'). The naive version loses key 19. The tombstone version finds it, and the later insert of 27 reuses slot 4.
Costs of tombstones
Tombstones fix correctness but add costs:
- Longer probes. A lookup for a missing key must walk past every tombstone until it reaches a truly empty slot. A table with many deletions can slow down even when few keys are live.
- Misleading load factor.
_livecounts only live keys, but tombstones fill slots and lengthen chains. A resize check should count live keys plus tombstones. - Cleanup by rebuilding. The usual cure is to rehash all live keys into a fresh table, which drops every tombstone. You can do this at the same capacity if the table is full of tombstones but has few live keys.
Separate chaining avoids this problem. Deleting from a bucket's list removes the entry outright, and no other key's lookup path changes.
Exercise
A table has 8 slots. Keys 5, 13, and 21 all have home slot 5 and are inserted in that order. You then remove 13 and call get(21). Which slots does the lookup probe, and what does it find in each?
Show answer
It probes slots 5, 6, and 7. Slot 5 holds key 5, which does not match. Slot 6 holds a tombstone, so the lookup keeps going. Slot 7 holds key 21, which matches, so the lookup returns its value.