Sub topic 8
Rehashing: moving entries into the new array
This chapter assumes you can read simple Python, know what a hash table does, and understand Big-O basics. You should also know that a table stores entries in buckets and that the load factor is size / capacity. Here you will see what happens after the load factor crosses its threshold: the table builds a larger array and moves every entry into it.
Why you cannot copy buckets across
A key's bucket is hash(key) % capacity. When the capacity changes, the modulus changes, so most keys belong in a different bucket than before. Copying the old bucket array into the front of a bigger one would leave entries where lookups no longer search for them.
For example, the keys 3, 11 and 19 all land in bucket 3 when the capacity is 8, because each leaves remainder 3 when divided by 8. At capacity 16, key 3 stays in bucket 3, key 11 moves to bucket 11, and key 19 goes back to bucket 3. Each entry's new position has to be computed again.
The rehash procedure
Rehashing has three steps:
- Allocate a new, empty bucket array with the new capacity.
- Visit every entry in the old array and compute its index using the new capacity.
- Insert the entry into that bucket of the new array, then discard the old array.
The implementation
This chained table triggers a resize inside put when the load factor exceeds max_load.
class ChainedHashTable:
def __init__(self, capacity=8, max_load=0.75):
self._buckets = [[] for _ in range(capacity)]
self._size = 0
self._max_load = max_load
def load_factor(self):
return self._size / len(self._buckets)
def _index(self, key):
return hash(key) % len(self._buckets)
def put(self, key, value):
bucket = self._buckets[self._index(key)]
for i, (k, _) in enumerate(bucket):
if k == key:
bucket[i] = (key, value)
return
bucket.append((key, value))
self._size += 1
if self.load_factor() > self._max_load:
self._resize(len(self._buckets) * 2)
def get(self, key, default=None):
for k, v in self._buckets[self._index(key)]:
if k == key:
return v
return default
def _resize(self, new_capacity):
old_buckets = self._buckets
self._buckets = [[] for _ in range(new_capacity)]
for bucket in old_buckets:
for key, value in bucket:
self._buckets[self._index(key)].append((key, value))
table = ChainedHashTable()
for key in (3, 11, 19, 1, 2, 4):
table.put(key, str(key))
print(len(table._buckets), table._buckets[3])
table.put(5, "5")
print(len(table._buckets), table._buckets[3], table._buckets[11])The output is:
8 [(3, '3'), (11, '11'), (19, '19')]
16 [(3, '3'), (19, '19')] [(11, '11')]The seventh insert gives a load factor of 7/8 = 0.875, which is above 0.75, so the capacity doubles. The three-entry chain in bucket 3 splits, and key 11 moves to bucket 11.
Details that cause bugs
- Replace the array before reinserting.
_indexreadslen(self._buckets). If you computed indexes whileself._bucketsstill pointed at the old array, every entry would go back to its old position. - Do not call
putfrom_resize. That would increment_sizea second time and could trigger a nested resize. Appending directly is correct because the size does not change and the keys are already known to be unique. - No equality checks are needed. Skipping the duplicate scan makes rehashing cheaper than
nnormal inserts. - Open addressing needs more care. Entries must be reinserted by probing in the new array, because collisions can still happen there. Deleted-slot markers (tombstones) are not copied, so a resize also cleans them out.
Cost
A rehash touches every entry exactly once, so it costs O(n) time. It also needs memory for both arrays at the same moment. For a chained table, the entry objects can be reused, but the new bucket array must exist alongside the old one. The single insert that triggers the resize is therefore slow, even though most inserts are fast. The next chapters explain why doubling keeps the average cost constant, and how incremental resizing spreads this one-time cost out.
Exercise
A table with capacity 8 holds the integer keys 5 and 13. It then doubles to capacity 16. Which buckets do the two keys occupy before and after the resize, and why does this show that buckets cannot be copied as they are?
Show answer
Before the resize, 5 % 8 = 5 and 13 % 8 = 5, so both keys share bucket 5. After the resize, 5 % 16 = 5 and 13 % 16 = 13, so key 13 moves to bucket 13. If the old bucket 5 were copied unchanged, a lookup for 13 would search bucket 13 and miss it. Each entry's index must be recomputed with the new capacity.