Sub topic 8
Deleting from an open-addressing table
This chapter assumes you know how linear probing inserts and finds keys, and that you are comfortable with the modulo operator and with load factor. Deletion looks like the easy operation, but in an open-addressing table it is the one that breaks lookups if you do it the obvious way.
Why deletion is different
In a chained table, a key lives in a bucket's list. Removing it means removing one list node, and no other key is affected.
In an open-addressing table, every entry sits in the slot array itself. A key that collided with an earlier key was pushed forward to the next free slot. A lookup for that key does not know where it ended up. It only knows the rule: start at the home index and walk forward until you find the key or reach an empty slot.
That rule makes an empty slot mean "no key can be further along this probe path." Deletion has to preserve that meaning.
The bug: marking the slot empty
Suppose the table has 8 slots and holds integer keys 1, 9, and 17. Python hashes small integers to themselves, so all three have home index 1 (1 % 8, 9 % 8, and 17 % 8 are all 1). They occupy slots 1, 2, and 3.
If you delete key 9 by setting slot 2 back to empty, key 17 becomes unreachable. A lookup for 17 starts at slot 1, sees a different key, moves to slot 2, sees an empty slot, and concludes 17 is absent. The key is still in the table, but the table can no longer find it.
_EMPTY = object()
_DELETED = object()
def lookup(slots, key):
n = len(slots)
i = hash(key) % n
for _ in range(n):
slot = slots[i]
if slot is _EMPTY:
return None
if slot is not _DELETED and slot[0] == key:
return slot[1]
i = (i + 1) % n
return None
def build():
slots = [_EMPTY] * 8
# 1, 9 and 17 all have home index 1, so they probe into slots 1, 2, 3
slots[1] = (1, "a")
slots[2] = (9, "b")
slots[3] = (17, "c")
return slots
naive = build()
naive[2] = _EMPTY # wrong: erases the probe path
print(lookup(naive, 17))
safe = build()
safe[2] = _DELETED # right: leaves a marker
print(lookup(safe, 17))The first line prints None and the second prints c. Only the marker in the slot differs.
Tombstones
The standard fix is a tombstone: a special marker stored in the slot of a deleted entry. It is a third slot state, alongside "empty" and "holds a live entry".
| Slot state | Lookup behavior | Insert behavior |
|---|---|---|
| Empty | Stop. The key is absent. | May be used for a new entry. |
| Tombstone | Skip it and keep probing. | May be reused for a new entry, after confirming the key is not further along. |
| Live entry | Compare keys. Return the value on a match, otherwise keep probing. | Overwrite if the key matches, otherwise keep probing. |
The lookup loop in the code above already contains the tombstone rule. It stops only at _EMPTY, and it skips _DELETED without comparing keys.
The n-slot cap in the diagram matters. If every slot is either live or a tombstone, no empty slot exists to stop the walk. Without the cap, a lookup for a missing key would loop forever.
Inserting around tombstones
Insertion has two jobs that pull in opposite directions.
- It must not create a duplicate. If the key already exists further along the probe path, past a tombstone, the insert must update that entry instead of adding a second one.
- It should reuse tombstones. Otherwise deleted slots are never recycled, and the table fills with markers.
The simplest correct approach, used below, is to search first. If the key exists, overwrite it. If not, walk from the home index and take the first slot that is empty or a tombstone. This does two probe walks for a new key, but it is easy to get right. A faster version remembers the first tombstone seen during the search and inserts there if the search ends at an empty slot.
A complete table with deletion
This is the linear-probing table with tombstones. It tracks two counters: _live counts real entries, and _used counts live entries plus tombstones.
_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. Three details are worth checking in the code.
removedecrements_livebut leaves_usedunchanged, because the slot is still occupied by a marker.putincrements_usedonly when it fills an empty slot. Reusing a tombstone does not change_used.- The resize check uses
_used, not_live. Tombstones lengthen probe sequences just like live entries do, so they count toward load.
Tombstones accumulate
Tombstones are never cleared by remove. They disappear only when a resize rebuilds the table, because _resize re-inserts live entries and drops markers. A workload that inserts and deletes many different keys can therefore fill the table with markers while holding almost no data.
t = ProbingHashTable()
for i in range(100):
t.put(i, i)
t.remove(i)
print(t._live, t._used, len(t._slots))This prints 0 40 128. The table holds nothing, yet it has grown to 128 slots. Each time _used crossed the load limit, put doubled the capacity even though the rebuild found no live entries to carry over.
The fix is to decide the new capacity from _live, not _used. When the check fails because of tombstones, rebuild at the same capacity. When it fails because of real data, double. Production tables apply the same idea: they rebuild to clean out tombstones without growing.
Alternatives to tombstones
Tombstones are not the only way to delete from a linear-probing table.
- Backward-shift deletion. After removing an entry, scan the following slots in the cluster and move back any entry whose home index lets it legally occupy the freed slot. No markers are left behind, and probe lengths shrink immediately. The rule for deciding whether an entry may move is subtle and easy to get wrong with wraparound. Robin Hood hashing uses this approach.
- Rebuild on a schedule. Keep tombstones but trigger a clean rebuild when the marker count passes a threshold.
- Avoid deletion. Some append-only workloads never delete, which removes the problem.
Separate chaining avoids the issue completely, which is one reason it is a common default when deletions are frequent.
Common errors
- Setting a deleted slot to empty, which cuts probe paths for other keys.
- Stopping a lookup at a tombstone instead of skipping past it.
- Inserting at the first tombstone without checking that the key does not already exist later in the path, which creates duplicates.
- Counting only live entries toward the load factor.
- Having no cap on the probe loop, so a lookup in a table with no empty slot never ends.
Exercise
A table with 8 slots uses linear probing. Keys 2, 10, and 18 all have home index 2 and sit in slots 2, 3, and 4. You remove key 10 using a tombstone, then insert key 26 (home index 2). Which slot does key 26 end up in, and what happens to the _used counter in the table above?
Show answer
The search for 26 finds no match and ends at empty slot 5, so 26 is absent. The insert walk then starts at slot 2 and takes the first slot that is empty or a tombstone. Slot 2 holds key 2 and slot 3 holds the tombstone, so key 26 goes into slot 3. Because the slot was a tombstone and not empty, _used stays the same. _live increases by one.
Exercise
Why does a lookup for a missing key in a table with no empty slots, only live entries and tombstones, need a limit of n probes?
Show answer
The search normally stops at an empty slot. If none exists, the walk wraps around forever. Limiting it to n probes guarantees the loop ends after visiting every slot once, and the lookup then reports the key as absent.