Collisions, Load Factor and Resizing
Compare separate chaining and open addressing, trace linear probing with tombstones and primary clustering, see how CPython dict probes, and trace why resizing doubles capacity and rehashes every key.
Contentsand lesson path
On this page
- Why it matters
- Two collision families: separate chaining vs open addressing
- Linear probing, tombstones and primary clustering
- Load factor and why resizing must rehash every key
- Check your understanding
- Apply it
- Review prompt
Lessons of Hashing & Hash Tables
- From Keys to Buckets Concept · 20 min
- Collisions, Load Factor and Resizing Concept · 20 min
- Lab: Build a Chained Hash Map Lab · 30 min
- Counting, Grouping and Complement Lookups Worked example · 25 min
- Custom Keys and Adversarial Inputs Concept · 15 min
- Check: Hashing Problem Set Knowledge check · 8 questions
What you will learn
- Implement a hash map with separate chaining and load-factor-based resizing that passes randomized tests against dict.
- Explain when hash operations degrade to O(n) and what makes a key hashable, including consistent __hash__ and __eq__ on custom classes.
- Trace insert, lookup and delete in an open-addressing table with linear probing, using tombstones so deletions do not break probe sequences, and explain how clustering ties performance to the load factor.
Prerequisites: Complexity Analysis
01. Why it matters
In From Keys to Buckets, "ada" and "guido" both landed in bucket 6. Compressing an unbounded set of keys into m buckets makes collisions unavoidable—with just 23 random keys across 365 buckets, the probability of at least one collision is already 50.7%. A hash table must keep every colliding key reachable without overwriting earlier entries.
How a table resolves collisions and controls how full it gets determines both lookup speed and deletion logic. In separate chaining, growing past capacity slows buckets down gradually; in open addressing, deletions require tombstone markers and, with linear probing, full tables suffer primary clustering unless the table resizes well before it fills.
02. Two collision families: separate chaining vs open addressing
Hash tables resolve collisions with one of two strategies:
- Separate chaining: each slot
buckets[i]holds a small secondary container (such as a Pythonlistor linked list) containing every(key, value)pair whose compressed hash equalsi. Lookups hashkey, jump tobuckets[idx], and scan only that bucket's chain. Because each bucket can hold multiple pairs, separate chaining still works whenn > m, though chains grow longer. - Open addressing: every
(key, value)entry sits directly inside the main table array with no per-bucket lists. When a key's home slot is occupied by a different key, the table follows a deterministic probe sequence across other array slots until it finds a matching key or an empty slot. Avoiding per-bucket list allocations saves pointer overhead and improves CPU cache locality, at two costs: the table cannot hold more entries than slots (n <= m), and the simplest correct deletion leaves a tombstone marker rather than clearing the slot to empty (linear probing can instead shift later entries back).
Separate chaining (buckets = lists): Open addressing (flat slots):
[0] -> [("grace", 2)] [0] ("grace", 2)
[1] -> [] [1] EMPTY
... ...
[5] -> [] [5] TOMBSTONE (deleted)
[6] -> [("ada", 1), ("guido", 4)] [6] ("ada", 1)
[7] -> [("linus", 3)] [7] ("guido", 4) <-- probed +103. Linear probing, tombstones and primary clustering
In linear probing, if home slot h = hash(key) % m is busy, you inspect (h + 1) % m, (h + 2) % m, and so on, wrapping around the end of the array. Every slot is in one of three states: EMPTY (never occupied), OCCUPIED (holds (key, value)), or TOMBSTONE (previously held an entry that was deleted).
Trace why three states are required instead of two. Suppose m = 7 and keys "k0", "k7", and "k14" all share home slot 3. Inserting them in order puts "k0" at 3, "k7" at 4, and "k14" at 5. Now delete "k7":
- Why
EMPTYbreaks lookup: if deletion reset slot4toEMPTY, a later lookup for"k14"starts at home slot3("k0"), steps to slot4, seesEMPTY, and concludes"k14"is absent—even though"k14"is sitting at slot5! - How
TOMBSTONEfixes lookup and delete: marking slot4asTOMBSTONEtells lookups to keep probing past slot4until they either match"k14"at slot5or reach a trueEMPTYslot. - Why
insertcannot stop at the first tombstone: suppose you next callput("k14", 99)to update"k14". At slot4you seeTOMBSTONE. Ifputoverwrote slot4immediately, you would create a duplicate"k14"at4while the old"k14"stayed at5! Correctputremembersfirst_tombstone = 4, keeps probing until it either finds"k14"(and updates slot5in place) or hitsEMPTYat slot6(proving the key is genuinely new, so it can safely write into the savedfirst_tombstoneslot4).
import random
EMPTY = ('EMPTY', None)
TOMBSTONE = ('TOMB', None)
class LinearProbingMap:
def __init__(self, capacity: int = 7) -> None:
self.slots: list[tuple[object, object]] = [EMPTY] * capacity
def _home(self, key: str) -> int:
# Map keys k0, k7, k14, k21 to slot 3 to force linear collisions.
return (int(key[1:]) + 3) % len(self.slots)
def put(self, key: str, value: int) -> None:
m = len(self.slots)
idx = self._home(key)
first_tombstone: int | None = None
for _ in range(m):
slot = self.slots[idx]
if slot is EMPTY:
target = first_tombstone if first_tombstone is not None else idx
self.slots[target] = (key, value)
return
if slot is TOMBSTONE:
if first_tombstone is None:
first_tombstone = idx
elif slot[0] == key:
self.slots[idx] = (key, value)
return
idx = (idx + 1) % m
if first_tombstone is not None:
self.slots[first_tombstone] = (key, value)
return
raise RuntimeError("Table full")
def get(self, key: str) -> int | None:
m = len(self.slots)
idx = self._home(key)
for _ in range(m):
slot = self.slots[idx]
if slot is EMPTY:
return None
if slot is not TOMBSTONE and slot[0] == key:
return slot[1] # type: ignore[return-value]
idx = (idx + 1) % m
return None
def delete(self, key: str) -> bool:
m = len(self.slots)
idx = self._home(key)
for _ in range(m):
slot = self.slots[idx]
if slot is EMPTY:
return False
if slot is not TOMBSTONE and slot[0] == key:
self.slots[idx] = TOMBSTONE
return True
idx = (idx + 1) % m
return False
lp = LinearProbingMap(capacity=7)
for k, v in [("k0", 10), ("k7", 20), ("k14", 30)]:
lp.put(k, v)
print("inserts:", [s[0] for s in lp.slots])
lp.delete("k7")
print("del k7: ", [s[0] for s in lp.slots])
print("get k14:", lp.get("k14"))
lp.put("k14", 99)
print("upd k14:", [s[0] for s in lp.slots], lp.get("k14"))
lp.put("k21", 40)
print("add k21:", [s[0] for s in lp.slots])
def measure_clustering(m: int = 200) -> None:
rng = random.Random(42)
keys = rng.sample(range(100_000), int(m * 0.90))
table: list[int | None] = [None] * m
for step, key in enumerate(keys, start=1):
idx = key % m
while table[idx] is not None:
idx = (idx + 1) % m
table[idx] = key
if step in (50, 100, 150, 180):
total_probes = 0
for present in keys[:step]:
p_idx = present % m
probes = 1
while table[p_idx] != present:
p_idx = (p_idx + 1) % m
probes += 1
total_probes += probes
max_run = cur = 0
for slot in table:
cur = cur + 1 if slot is not None else 0
max_run = max(max_run, cur)
print(
f"alpha={step/m:.2f} avg_hit_probes={total_probes/step:.2f} "
f"max_cluster={max_run}"
)
measure_clustering()inserts: ['EMPTY', 'EMPTY', 'EMPTY', 'k0', 'k7', 'k14', 'EMPTY']
del k7: ['EMPTY', 'EMPTY', 'EMPTY', 'k0', 'TOMB', 'k14', 'EMPTY']
get k14: 30
upd k14: ['EMPTY', 'EMPTY', 'EMPTY', 'k0', 'TOMB', 'k14', 'EMPTY'] 99
add k21: ['EMPTY', 'EMPTY', 'EMPTY', 'k0', 'k21', 'k14', 'EMPTY']
alpha=0.25 avg_hit_probes=1.32 max_cluster=6
alpha=0.50 avg_hit_probes=1.48 max_cluster=8
alpha=0.75 avg_hit_probes=1.98 max_cluster=13
alpha=0.90 avg_hit_probes=2.78 max_cluster=51Look at the clustering numbers as load factor alpha = n / m rises from 0.25 to 0.90: between 0.75 and 0.90, max_cluster jumps nearly fourfold from 13 slots to 51 slots! Why does linear probing clump even with random keys? This effect is primary clustering: once a contiguous block of k occupied slots forms, any new key whose home slot lands anywhere inside those k slots (or right at the start) walks to the end of the run and extends it to k + 1. Longer runs become larger targets and eventually merge with neighbouring runs. Also notice that tombstones behave like occupied slots during unsuccessful lookups—if a table holds many tombstones and few empty slots, misses still walk long runs until hitting EMPTY. Real open-addressing tables therefore count both active entries and tombstones (used + tombstones) toward the resize or rebuild trigger so a rebuild sweeps tombstones away (unlike our toy LinearProbingMap, which never cleans them up).
How CPython dict probes (overview): CPython dict is an open-addressing hash table, not separate chaining, with two structural twists. First, it splits storage into a compact open-addressing index table (dk_indices, holding slot markers such as empty -1 or dummy tombstone -2, or an entry index) and a dense entries array (dk_entries, appended in insertion order). Second, instead of linear idx + 1, CPython mixes upper hash bits into each collision step (perturb >>= 5; j = (5 * j + 1 + perturb) & mask), so keys sharing a lower-bit bucket diverge onto different probe paths rather than piling into one linear run. To prevent probe lengths from climbing as free slots disappear, CPython resizes its dict table once about two-thirds of the slots have been used (deleted entries count until the next resize: 8 -> 16 -> 32, growing after 5, 10, and 21 used entries).
04. Load factor and why resizing must rehash every key
The load factor is alpha = n / m, where n is the number of active entries and m is the number of buckets or slots. Under separate chaining, alpha equals the average chain length. Keeping alpha <= 0.75 keeps expected chain length below 1, so get, put, and delete inspect roughly one entry on average (O(1) expected time). Keep the boundary clear: keeping alpha <= 0.75 bounds the average chain on well-spread keys, yet adversarial keys with identical hashes can still pile into one chain (O(n) worst case).
When n / m crosses the threshold, the table doubles capacity (m -> 2m, e.g., 8 -> 16). Crucially, existing entries cannot remain at their old indices 0..7: after resizing, lookups compute hash(key) % 16, not % 8. Every entry must be re-inserted into the new 16-bucket array at hash(key) % 16. As shown in Worst Case, Average Case and Amortized Cost, doubling m makes this O(n) rehash rare enough that put stays O(1) amortised.
def show_rehash(keys: list[str], old_m: int, new_m: int) -> None:
def toy(k: str) -> int:
return sum((i + 1) * ord(ch) for i, ch in enumerate(k))
old_b: list[list[str]] = [[] for _ in range(old_m)]
for k in keys:
old_b[toy(k) % old_m].append(k)
new_b: list[list[str]] = [[] for _ in range(new_m)]
for bucket in old_b:
for k in bucket:
new_b[toy(k) % new_m].append(k)
print(f"old m={old_m}, load={len(keys)/old_m:.2f}:")
print(" ", old_b)
print(f"new m={new_m}, load={len(keys)/new_m:.2f}:")
print(" ", new_b[:8])
print(" ", new_b[8:])
show_rehash(["cat", "dog", "ant", "bee", "owl", "fox", "elk"], old_m=8, new_m=16)old m=8, load=0.88:
[[], ['cat', 'ant', 'owl'], [], ['bee'], ['fox'], [], ['elk'], ['dog']]
new m=16, load=0.44:
[[], ['cat', 'owl'], [], [], [], [], [], ['dog']]
[[], ['ant'], [], ['bee'], ['fox'], [], ['elk'], []]Look at "ant" above: before resizing, "ant" shared bucket 1 (% 8 == 1) with "cat" and "owl". Doubling m from 8 to 16 moved "ant" to bucket 9 (% 16 == 9), breaking up the 3-way collision and cutting load factor from 0.88 to 0.44. Notice why "cat" and "owl" stayed together in bucket 1: their hashes happened to agree modulo 16 too. Doubling spreads roughly half of colliding keys into old_idx + old_m rather than splitting every single pair.
What if you resized by adding + 8 slots instead of doubling? Just like fixed-step array growth, rehashes would fire every 6 inserts (0.75 * 8), turning n inserts into O(n^2) total work. And what if you chose alpha > 0.1 instead of 0.75? A threshold of 0.1 needs about 7.5x as many slots for the same n, with little lookup gain.
Trade-off and when not to rely on automatic resizing: in CPython dict and set, deleting keys with d.pop(k) or del d[k] marks tombstones and does not shrink the internal table automatically (popitem(), which removes from the end, is the exception)—iterating over a 5-item dict that once held 1,000,000 entries still walks the large former table until a future resize or until you copy into a fresh dict. Likewise, if your service cannot tolerate an occasional O(n) resize pause on a critical-path put, pre-size the table or use incremental rehashing.
05. Check your understanding
06. Apply it
Extend measure_clustering() above to count unsuccessful lookup probes (search for 200 absent keys at each load factor 0.25, 0.50, 0.75, 0.90 until hitting None) and compare how much faster unsuccessful probe length explodes near 0.90 than successful probe length.
Next, build your own complete chained hash map and test it differentially against Python dict in Lab: Build a Chained Hash Map.
07. Review prompt
Without looking back:
- Why must linear probing use a
TOMBSTONEmarker instead of resetting a deleted slot toEMPTY, and why mustputstill probe past the first tombstone untilEMPTY? - What causes primary clustering in linear probing, and how does CPython
dictprobing avoid it? - Why must every entry be re-indexed with
% new_mwhen a hash table doubles its buckets? - Why should an open-addressing table trigger a rebuild based on
used + tombstonesrather thanusedalone?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.