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 also assumes you can read short Python programs.
The problem resizing solves
A chained hash table keeps an array of buckets. Each bucket holds a list of the entries whose hash maps to it. With n entries and m buckets, the load factor is α = n / m. If hashes spread evenly, the average chain holds α entries, so a lookup or insertion scans about 1 + α items.
That figure holds only while α stays bounded. If the bucket count is fixed and n keeps growing, α grows linearly with n and every operation slows down. Resizing keeps α below a limit by adding buckets as entries arrive.
Resizing has a cost of its own. Reaching a bucket from a key uses hash(key) % len(buckets). When len(buckets) changes, almost every entry belongs in a different bucket. You cannot copy the old bucket lists across. You must recompute the position of every entry, which is why this step is called rehashing.
The resize rule
The rule has two parts:
- After each insertion of a new key, check whether
n > MAX_LOAD * m. - If so, allocate
2mbuckets and reinsert every entry.
Updating the value of an existing key does not change n, so it never triggers a resize.
Counting the rehash work
The program below is the chained table from the plan, with two counters added. moves counts entries reinserted during resizes. resizes counts the resizes themselves.
class CountingHashTable:
MAX_LOAD = 0.75
def __init__(self):
self._buckets = [[] for _ in range(8)]
self._size = 0
self.moves = 0 # entries reinserted by resizes
self.resizes = 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.moves += 1
self._buckets = new_buckets
self.resizes += 1
for n in (100, 1000, 10000, 100000):
t = CountingHashTable()
for i in range(n):
t.put(i, i)
assert t.moves < 2 * n + n.bit_length()
print(n, t.resizes, t.moves, round(t.moves / n, 3))The output is:
100 5 191 1.91
1000 8 1538 1.538
10000 11 12293 1.229
100000 15 196617 1.966The moves per insertion never reach 2, and the ratio does not climb as n grows. It moves up and down because it depends on how far n is past the most recent resize. At n = 100000 the table has just resized at 98305 entries, so the ratio is near its peak. At n = 10000 the last resize was at 6145 entries, so much of the rehash cost has been spread over fewer insertions than the cycle allows and the ratio is low.
Aggregate proof
Start with 8 buckets. A resize happens when the size first exceeds 0.75m, and at that moment the table moves ⌊0.75m⌋ + 1 ≤ 0.75m + 1 entries. The bucket counts that trigger a resize are 8, 16, 32, and so on up to M/2, where M is the final bucket count. Summing:
- The geometric series
8 + 16 + … + M/2is less thanM. - So the total moves are less than
0.75M + k, wherek = log₂(M/8)is the number of resizes.
Now relate M to n. The last resize happened when the table held more than 0.75 · M/2 = 0.375M entries. So n > 0.375M, which gives M < n / 0.375 ≈ 2.67n. Substituting:
total moves < 0.75 · 2.67n + k = 2n + kSince k is at most log₂ n, the total rehash work is under 2n + log₂ n moves. Add the n ordinary insertions and the total is O(n). Dividing by n operations gives O(1) amortised per insertion.
The key fact is the same as for the dynamic array. Each resize costs about twice as much as the previous one, so the last resize pays for roughly half of everything, the one before for a quarter, and the series sums to a constant multiple of n.
Cross-check with the accounting method
Suppose a resize has just produced 2m buckets. The next resize fires at 0.75 · 2m = 1.5m entries and will move about 1.5m entries. Between the two resizes there are about 0.75m insertions, since the table already held about 0.75m entries. Spreading 1.5m moves over 0.75m insertions gives 2 credits per insertion. Add 1 unit for the insertion itself and each put is charged a flat 3 units. This matches the bound from the aggregate method: no more than about 2 moves per insertion, plus the insertion.
What one insertion can cost
Amortised O(1) describes the average over a sequence. A single put can still be expensive. The next snippet measures the most expensive single insertion in a run of 1000.
t = CountingHashTable()
worst = 0
for i in range(1000):
before = t.moves
t.put(i, i)
worst = max(worst, t.moves - before)
print(worst)This prints 769. One insertion out of 1000 moved 769 entries. The total over all 1000 insertions is still only 1538 moves.
Design decisions
Choice of maximum load factor
| Max load | Memory use | Chain length | Resize frequency |
|---|---|---|---|
| 0.5 | Higher | Shorter | More often |
| 0.75 | Moderate | Moderate | Moderate |
| 1.0 | Lower | Longer | Less often |
A lower limit trades memory for shorter chains. Resizes happen sooner, but the amortised bound still holds because the rehash total stays proportional to n. Only the constant changes.
Choice of growth factor
Doubling is not special. Any constant factor g > 1 gives a geometric series and O(1) amortised cost. A smaller factor wastes less memory but resizes more often, so the constant is larger. A larger factor resizes less often but leaves more unused buckets.
Growing by a fixed number of buckets, such as m + 8, breaks the argument. The number of resizes becomes proportional to n, each moves Θ(n) entries, and total work becomes quadratic. This is the same failure as additive growth in a dynamic array.
Why the cost is spread over duplicates correctly
Only insertions of new keys can trigger a resize. A workload that repeatedly overwrites existing keys does no rehashing at all. The bound counts operations that add entries, which is what the credits in the accounting argument assume.
Where the argument stops
The amortised analysis covers the cost of resizing only. It does not cover the cost of scanning a chain, and that depends on the hash function.
- With evenly spread hashes, the expected chain length is at most
α ≤ 0.75, so the scan is O(1) in expectation. - If many keys share a hash value, they land in one bucket. Resizing cannot separate them, because they still map to the same index in the larger table. A scan of that chain costs O(n) however often the table grows.
Python's hash of a small integer is the integer itself, so the keys 0..n-1 in the examples spread almost perfectly. Real keys such as strings rely on a good hash function for the same effect.
Exercise
A chained table starts with 8 buckets and doubles when the size exceeds 0.5 times the bucket count. At which insertion does the first resize occur, and how many entries does it move?
Show answer
The first resize occurs when the size exceeds 0.5 × 8 = 4, which is the 5th new key. At that moment the table holds 5 entries, so the resize moves 5 entries into the new 16 buckets.
Exercise
A programmer changes the growth rule from 2 * len(buckets) to len(buckets) + 8. Why is insertion no longer O(1) amortised?
Show answer
Each resize adds only 8 buckets, so the table must resize after about every 6 more insertions to keep the load factor under 0.75. That makes the number of resizes proportional to n. A resize at size s moves about s entries, so the total moves over n insertions is roughly the sum of s over about n/6 resizes, which is Θ(n²). The cost per insertion is therefore Θ(n), not constant.