Sub topic 9
Resizing a Hash Table: Amortised O(1) Insertion
This chapter assumes you know Big-O notation, how a chained hash table stores entries in buckets, and how the aggregate method totals the cost of a sequence of operations. It applies the same argument to hash table insertion.
The problem a fixed table cannot solve
A chained hash table with a fixed number of buckets m holds n entries. The load factor is n / m, the average chain length. If m never changes, the load factor grows without bound as n grows. A lookup then costs about n / m steps, which is O(n) when m is a constant.
The fix is to keep the load factor below a limit by resizing. When an insertion pushes the load factor over the limit, allocate a bigger bucket array and move every entry into it.
Why rehashing is required
You cannot copy the old buckets into the new array unchanged. The bucket index is hash(key) % len(buckets), so a new length gives most keys a new index. Every entry must be hashed again and placed in the new array. That is rehashing, and it costs O(n) for a table with n entries.
The implementation
class ChainedHashTable:
MAX_LOAD = 0.75
def __init__(self):
self._buckets = [[] for _ in range(8)]
self._size = 0
def put(self, key, value):
bucket = self._buckets[hash(key) % len(self._buckets)]
for i, (k, _) in enumerate(bucket):
if k == key:
bucket[i] = (key, value)
return
bucket.append((key, value))
self._size += 1
if self._size > self.MAX_LOAD * len(self._buckets):
self._grow()
def get(self, key, default=None):
bucket = self._buckets[hash(key) % len(self._buckets)]
for k, v in bucket:
if k == key:
return v
return default
def _grow(self):
new_buckets = [[] for _ in range(2 * len(self._buckets))]
for bucket in self._buckets:
for k, v in bucket:
new_buckets[hash(k) % len(new_buckets)].append((k, v))
self._buckets = new_buckets
table = ChainedHashTable()
for i in range(1000):
table.put(i, i * i)
assert table.get(31) == 961The table starts with 8 buckets. Insertion number 7 makes the size 7, which is more than 0.75 × 8 = 6, so _grow doubles the bucket count to 16. The next resize happens when the size exceeds 12, and so on. The load factor never stays above 0.75 after an insertion finishes.
The aggregate argument
Count the cost of n insertions, with one unit for placing an entry and one unit for each entry moved during a resize.
- Placing the entries costs
nunits in total, ignoring the chain scan, which is bounded by the load factor and covered below. - Resizes happen when the size passes
0.75 × 8, then0.75 × 16, then0.75 × 32, and so on. A resize at bucket countmmoves about0.75mentries. - The bucket counts form a doubling sequence. The sum of
0.75moverm = 8, 16, 32, ..., Mis less than0.75 × 2M, whereMis the last bucket count, andMis at most aboutn / 0.375. The total rehash work is therefore a constant multiple ofn.
Total work is n plus a constant times n, so the amortised cost per insertion is O(1). This is the same geometric-series argument as for the dynamic array. Doubling matters here for the same reason: each resize does work proportional to the table size, but the next resize is that many insertions away.
Two costs, not one
The O(1) bound has two parts that come from different arguments.
| Part | What it covers | Where the bound comes from |
|---|---|---|
| Resizing | Moving entries into a larger array | Amortised: doubling and the geometric series |
| Chain scan | Walking one bucket to find or add a key | Expected: the load factor stays at most 0.75, and the hash spreads keys evenly |
The resizing bound holds for any sequence of insertions. The chain-scan bound relies on the hash function behaving well. If many keys land in one bucket, a single put can scan a long chain no matter how large the table is. Later chapters separate these two kinds of average.
Exercise
A table starts with 8 buckets and doubles when the size exceeds 0.75 × the bucket count. After how many insertions of distinct keys does the second resize (from 16 to 32 buckets) happen, and how many entries are rehashed in it?
Show answer
The first resize happens at size 7 (7 > 6). The table then has 16 buckets, and the threshold is 12. The second resize happens when the size reaches 13 (13 > 12), on the 13th insertion. All 13 entries are rehashed into the 32-bucket array.