Sub topic 11
Open Addressing, Tombstones and Rebuilds
This chapter assumes you know the following:
- Chained hash tables and the load factor.
- Doubling and rehashing, as used for amortised O(1) insertion.
- The aggregate and accounting methods.
- Big-O notation and short Python programs.
Chained tables resize because buckets grow too long. Open addressing resizes for that reason too. It has a second reason that chaining does not: deletions leave debris that must be cleaned up by rebuilding.
What open addressing changes
In open addressing, every entry lives directly in the slot array. There are no linked lists or bucket lists. A key hashes to a home slot. If that slot is taken, the table probes (tries) other slots in a fixed order until it finds a free one. This chapter uses linear probing, which tries the home slot, then the next slot, then the next, and wraps around at the end.
| Property | Chained table | Open addressing (linear probing) |
|---|---|---|
| Storage | Array of buckets, each holding a list | One flat array of slots |
| Load factor can exceed 1 | Yes | No, the table holds at most one entry per slot |
| Cache behaviour | Pointer chasing | Neighbouring slots, usually faster |
| Deletion | Remove from one bucket | Needs a marker or a repair step |
| Sensitivity to high load | Gradual | Sharp, probe sequences grow quickly |
The load factor α is the number of occupied slots divided by the slot count. For linear probing with a good hash function, the classical estimates of expected probes are:
- An unsuccessful lookup takes about ½(1 + 1/(1−α)²) probes. At α = 0.5 this is 2.5 probes. At α = 0.9 it is 50.5 probes.
- A successful lookup takes about ½(1 + 1/(1−α)) probes. At α = 0.5 this is 1.5 probes.
Because of this curve, open-addressing tables resize at a much lower maximum load than chained tables. This chapter uses 0.5.
Why deletion needs tombstones
Suppose keys A and B hash to the same home slot. A is stored there and B sits one slot later. Now delete A by marking its slot empty. A lookup for B starts at the home slot, sees an empty slot, and concludes that B is absent. The probe chain is broken.
The standard fix is a tombstone, a special marker that means "an entry was here, keep probing past me". Each slot is in one of three states:
- Empty: never used since the last rebuild. A lookup stops here.
- Live: holds a key and value.
- Tombstone: held an entry that was deleted. A lookup continues past it, and an insert may reuse it.
The hidden cost: tombstones count as load
A tombstone is not a live entry, but it still lengthens probe chains. A lookup that hits an empty slot stops, and tombstones are not empty. A table with few live entries and many tombstones therefore behaves like a nearly full table. In the extreme case, every slot is a tombstone or live, no slot is empty, and an unsuccessful lookup scans the entire array.
So the resize policy must track used slots, meaning live entries plus tombstones, and not just live entries. Reusing a tombstone for a new key does not change the used count, because that slot was already counted. Only an insert into an empty slot raises it.
When used slots exceed the maximum load, the table rebuilds. A rebuild allocates a fresh array and re-inserts only the live entries, which discards every tombstone. The new capacity depends on how many live entries remain:
- If many live entries remain, the table has genuinely grown, so it doubles.
- If few remain, the load came mostly from tombstones, so it rebuilds at the same capacity.
Implementation
EMPTY = object()
TOMBSTONE = object()
class OpenAddressingTable:
MAX_LOAD = 0.5 # applies to live entries plus tombstones
def __init__(self, capacity=8):
self._slots = [EMPTY] * capacity
self._live = 0
self._used = 0 # live entries plus tombstones
self.rebuilds = 0
def __len__(self):
return self._live
@property
def capacity(self):
return len(self._slots)
def _probe(self, key):
n = len(self._slots)
i = hash(key) % n
for _ in range(n):
yield i
i = (i + 1) % n
def get(self, key, default=None):
for i in self._probe(key):
slot = self._slots[i]
if slot is EMPTY:
return default
if slot is not TOMBSTONE and slot[0] == key:
return slot[1]
return default
def put(self, key, value):
first_free = None # first tombstone seen on the probe path
for i in self._probe(key):
slot = self._slots[i]
if slot is EMPTY:
break
if slot is TOMBSTONE:
if first_free is None:
first_free = i
elif slot[0] == key:
self._slots[i] = (key, value)
return
# The key is absent. The load limit guarantees an EMPTY slot exists.
if first_free is not None:
self._slots[first_free] = (key, value)
self._live += 1 # tombstone already counted in _used
else:
self._slots[i] = (key, value)
self._live += 1
self._used += 1
if self._used > self.MAX_LOAD * len(self._slots):
self._rebuild()
def delete(self, key):
for i in self._probe(key):
slot = self._slots[i]
if slot is EMPTY:
return False
if slot is not TOMBSTONE and slot[0] == key:
self._slots[i] = TOMBSTONE
self._live -= 1 # _used is unchanged
return True
return False
def _rebuild(self):
capacity = len(self._slots)
if self._live > capacity // 4:
capacity *= 2 # real growth, not just tombstones
old = self._slots
self._slots = [EMPTY] * capacity
self._live = 0
self._used = 0
self.rebuilds += 1
for slot in old:
if slot is not EMPTY and slot is not TOMBSTONE:
self.put(slot[0], slot[1])
# Churn: keep about 5 live keys while inserting 10,000 distinct keys.
table = OpenAddressingTable()
for i in range(10000):
table.put(i, i * i)
if i >= 4:
table.delete(i - 4)
assert len(table) == 4
assert table.get(9999) == 9999 * 9999
assert table.get(0) is None
assert table.capacity <= 64
print(len(table), table.capacity, table.rebuilds)The workload inserts 10,000 distinct keys but never holds more than five. Every deleted key leaves a tombstone. Without rebuilds, tombstones would fill the array. With the rebuild rule, the capacity stays small and the program completes hundreds of rebuilds. Tombstone cleanup, not growth, drives those rebuilds.
The rebuild calls put, and put can itself trigger a rebuild. This does not recurse. When the rebuild runs, used slots exceed half the capacity. In the same-capacity branch, the live count is at most a quarter of the capacity. In the doubling branch, the live count is at most half the old capacity plus one, which is about a quarter of the new capacity. In both cases the re-inserted entries stay under the limit.
Amortised cost of the rebuild policy
A rebuild scans the whole array, so it costs Θ(capacity). Lookups and deletes are O(1) plus probing. The question is whether inserts stay O(1) amortised. Apply the aggregate method between two consecutive rebuilds.
- Let
cbe the capacity just after a rebuild. At that moment the table has used = live. - Only an insert into an empty slot raises the used count. Deletes and tombstone reuse do not.
- The next rebuild fires when used exceeds c/2. If the rebuild kept the capacity, the live count was at most c/4. Reaching the trigger therefore needs at least c/4 fresh-slot inserts.
- If the rebuild doubled the capacity to c, the live count was at most c/4 + 1. This follows from the analysis of the previous rebuild. Reaching the trigger again still needs about c/4 fresh-slot inserts.
- Each rebuild costs O(c), and at least c/4 inserts happened since the last one. Spread over those inserts, each pays O(4c / c) = O(1).
In the accounting method, this means each insert into a fresh slot is charged a constant number of credits. Those credits pay for the next scan. Deletes pay only for themselves, because a delete never moves the table closer to a rebuild. It leaves the used count unchanged, so the rebuild point is no closer.
The factor between the trigger (c/2) and the post-rebuild ceiling (c/4) keeps the policy from thrashing. This is the same gap-between-thresholds idea you saw in shrinking arrays. If the rebuild left the table right at the trigger, the next insert would rebuild again.
Expected versus amortised, again
The rebuild bound is amortised and holds for any sequence of operations. The probe count is an expected bound, and it needs the hash function to spread keys evenly. A poor hash function or an adversarial key set creates long clusters, and linear probing is especially sensitive to clustering. The O(1) claim for insert therefore combines two separate guarantees, each with its own failure mode.
Alternatives to tombstones
- Backward-shift deletion. For linear probing, a delete can pull later entries in the cluster back into the gap, so no marker is left. Deletion is more complex, but there is no tombstone debris and no cleanup rebuilds.
- Periodic rebuilds on a schedule. Some implementations rebuild after a fixed number of deletes. This is simpler than tracking used slots, but it can rebuild too often or too late.
- Real implementations. Python's
dictmarks deleted entries and rebuilds when the space for new entries runs out. This is the same pattern as in the code above.
The latency cost of a rebuild
A single rebuild touches every slot. For a table with millions of slots, that is a pause of milliseconds or more inside one put call. The amortised bound says the average is fine. It says nothing about the unlucky call. Latency-sensitive systems avoid this pause by moving entries to the new array a few at a time. That technique is incremental rehashing, and it is the subject of the next chapter.
Exercise
A table has capacity 16 and MAX_LOAD 0.5. It currently holds 3 live entries and 6 tombstones. The next insert uses an empty slot. Does a rebuild occur, and if so, what capacity does the table have afterwards (using the rule in this chapter)?
Show answer
The used count goes from 9 to 10, which exceeds 0.5 × 16 = 8, so a rebuild occurs. The live count after the insert is 4. The doubling test is live > capacity // 4, which is 4 > 4 and is false. The table rebuilds at capacity 16 and discards the 6 tombstones.
Exercise
Explain why deleting a key in this implementation never triggers a rebuild, and why that is consistent with the amortised argument.
Show answer
A delete turns a live slot into a tombstone. The used count (live plus tombstones) does not change, and the rebuild trigger depends only on the used count. The amortised argument charges rebuild cost to inserts into fresh slots, which are the only operations that raise the used count. Deletes cost O(1) probing and need no credits for rebuilding.