Sub topic 3
Resizing a Hash Table: Amortised O(1) Insertion
Assume you know Big-O notation, array indexing, and the basic idea of hashing. A chained hash table stores a list of entries in each bucket. Its load factor is:
\[ \alpha = \frac{\text{number of entries}}{\text{number of buckets}} \]
When the load factor exceeds a threshold such as 0.75, the table grows and rehashes every entry.
def put(table, key, value):
if table.size + 1 > 0.75 * len(table.buckets):
table.resize(2 * len(table.buckets))
index = hash(key) % len(table.buckets)
table.buckets[index].append((key, value))
table.size += 1A resize costs \(O(m)\) when the table contains \(m\) entries. However, after doubling, another resize requires roughly twice as many insertions. Across \(n\) insertions, the copied entries cost:
\[ 1 + 2 + 4 + \cdots + 2^k < 2n \]
The ordinary writes cost \(n\), so the total cost is less than \(3n\). Therefore insertion costs \(O(1)\) amortised, assuming hash operations and bucket searches have constant expected cost.
Expected versus amortised cost
These are different claims:
- Expected cost averages over the hash function or random input. It usually assumes collisions remain limited.
- Amortised cost averages over a sequence of operations. It holds for every operation sequence, although some individual operations may be expensive.
A resize can be both amortised \(O(1)\) and worst-case \(O(n)\). Expected analysis does not remove that single-operation cost.
Open addressing, tombstones, and rebuilds
Open addressing stores entries directly in the table and probes for an empty slot. Deletion often leaves a tombstone, a marker that preserves probe chains. Too many tombstones increase probe lengths. A rebuild creates a fresh table and reinserts live entries.
The same geometric-growth argument gives amortised bounds, but probe costs depend on the load factor and tombstone count.
Incremental rehashing
Incremental rehashing moves only a few old entries during each later operation. This spreads resize work across many operations and can improve worst-case latency. It requires tracking two tables and searching both while migration continues.
When amortised bounds are not enough
Use incremental resizing, a real-time data structure, or preallocation when pauses are unacceptable, such as in a latency-sensitive service or control loop.
Exercise
Why does doubling the bucket count make rehashing O(1) amortised per insertion?
Show answer
Each resize costs proportional to the current size, but the sizes form a geometric sequence whose total is less than twice the final number of entries.