Sub topic 11
Resizing and rehashing
This chapter assumes you know arrays and indexing, basic Python classes and tuples, average versus worst-case Big-O, and modulo arithmetic. You should also have read the chapter on load factor.
Why a table must grow
Load factor is the number of stored keys divided by the number of slots. As it rises, chains get longer in separate chaining, and probe sequences get longer in open addressing. Both slow lookups. The fix is to allocate a larger array and move every entry into it. This is called resizing. Re-placing the entries is called rehashing.
Typical thresholds:
| Strategy | Common maximum load factor |
|---|---|
| Separate chaining | about 1.0 |
| Open addressing | about 0.5 to 0.75 |
Open addressing needs a lower limit because every key lives in the array itself. A full table has no free slot to probe to.
Why you cannot just copy the array
A key's slot is hash(key) % capacity. When the capacity changes, the result changes too. Copying entries to the same index in a bigger array would make lookups look in the wrong place. Every key has to be reinserted using the new capacity.
def rehash(buckets, new_capacity):
new_buckets = [[] for _ in range(new_capacity)]
for bucket in buckets:
for key, value in bucket:
new_buckets[hash(key) % new_capacity].append((key, value))
return new_buckets
buckets = [[] for _ in range(4)]
for key in [3, 7, 11, 15]:
buckets[hash(key) % 4].append((key, key * 10))
print([[k for k, _ in b] for b in buckets])
buckets = rehash(buckets, 8)
print([[k for k, _ in b] for b in buckets])Small integers hash to themselves, so the output is predictable. All four keys start in one chain, then split across two slots:
[[], [], [], [3, 7, 11, 15]]
[[], [], [], [3, 11], [], [], [], [7, 15]]This is the same work ChainedHashMap._resize does. It builds a new array and reinserts each pair with _index, which now uses the new length.
When the check happens
The chained map checks after adding a new key. Many open-addressing tables check before inserting, so a free slot is always available.
Why double the capacity
Doubling makes inserts cheap on average. Rehashing at sizes 8, 16, 32 and so on copies at most about 2n entries over n inserts. That is O(1) amortized per insert. Growing by a fixed amount, such as 10 slots, rehashes so often that total work becomes O(n²).
A single insert that triggers a resize still costs O(n). Latency-sensitive systems may spread the copy over several operations, but that adds complexity.
Open addressing and tombstones
Rehashing in open addressing has two details:
- Reinsert only live entries. Tombstones are dropped, so a resize also cleans them out.
- Count tombstones toward the load that triggers a resize. They lengthen probe sequences just like live keys. A table with few live keys but many tombstones can need a same-size rehash.
Shrinking
Some tables shrink when the load factor falls low, for example below 0.25 after many deletions. Use a gap between the grow and shrink thresholds. If you grow at 1.0 and shrink at 0.9, inserting and deleting one key near the boundary would trigger a rehash every time.
Exercise
A ChainedHashMap starts with capacity 8 and resizes when size / capacity is greater than 1.0. Which insertion of a new distinct key triggers the first resize, and what is the new capacity?
Show answer
The 9th. After 8 keys the load factor is exactly 1.0, which is not greater than 1.0. The 9th key makes it 9/8 = 1.125, so the map resizes to capacity 16 and rehashes all 9 entries.