Sub topic 9
Load Factor and Resizing
A hash table is fast only while its buckets stay mostly empty. This chapter covers the number that measures how full the table is, the rule that grows it, and the cost of growing. It assumes you have read the earlier chapters on hash functions, bucket indexes, collisions, chaining, and linear probing. You should also be comfortable with introductory Big-O notation.
What the load factor measures
The load factor, usually written α (alpha), is the number of stored entries divided by the number of buckets:
α = n / m
Here n is the entry count and m is the bucket count. A table with 6 entries and 8 buckets has α = 0.75.
The load factor tells you how likely a collision is. With a good hash function, each key lands in a roughly random bucket, so a new key finds an occupied bucket more often as α rises.
- With chaining, α is the average chain length. It can exceed 1 because a bucket can hold many pairs.
- With open addressing, every entry occupies its own slot, so α cannot exceed 1. Performance gets much worse well before that point.
What the numbers look like
Under the usual assumption of uniform hashing, theory gives the expected number of slots or nodes examined by an unsuccessful lookup:
| Load factor α | Chaining (about 1 + α) | Linear probing (about ½(1 + 1/(1−α)²)) |
|---|---|---|
| 0.50 | 1.5 | 2.5 |
| 0.75 | 1.75 | 8.5 |
| 0.90 | 1.9 | 50.5 |
Chaining degrades gently. Linear probing degrades sharply as α approaches 1, because occupied slots form long runs that every later key must walk through. This is why probing tables use a lower maximum load than chained tables.
The resize rule
A hash table fixes a maximum load factor at construction. After each insertion, it checks whether α exceeds that limit. If it does, the table allocates a larger bucket array and moves every entry into it.
Typical limits:
- Java's
HashMapdefaults to 0.75 and doubles its capacity. - CPython's
dictkeeps its usable entries to about two thirds of its slots. - The probing table in this tutorial uses 0.5.
The exact value is a trade-off. A lower limit wastes memory on empty buckets but keeps lookups fast. A higher limit saves memory but lengthens chains or probe runs.
Why every entry must be rehashed
You cannot copy the old array into the new one and leave entries where they are. The bucket index is hash(key) % m, and m just changed. A key whose hash is 13 sits in bucket 5 when m is 8, but belongs in bucket 13 when m is 16.
Resizing therefore recomputes the index of every entry against the new capacity. Within a bucket, relative order is not preserved, and entries that collided before may now be separated. Open addressing has a second reason to rebuild: a probe sequence depends on the table size, so entries must be reinserted one by one.
A table that grows
This chained table doubles when α passes 0.75. It starts small so the resizes are easy to see.
class GrowingTable:
def __init__(self, capacity=4, max_load=0.75):
self._buckets = [[] for _ in range(capacity)]
self._size = 0
self._max_load = max_load
@property
def capacity(self):
return len(self._buckets)
@property
def load_factor(self):
return self._size / len(self._buckets)
def put(self, key, value):
bucket = self._buckets[hash(key) % self.capacity]
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(self.capacity * 2)
def _resize(self, new_capacity):
old = self._buckets
self._buckets = [[] for _ in range(new_capacity)]
for bucket in old:
for k, v in bucket:
self._buckets[hash(k) % new_capacity].append((k, v))
table = GrowingTable()
last = table.capacity
for n in range(1, 31):
table.put(n, n)
if table.capacity != last:
print(f"size={n} capacity={table.capacity} load={table.load_factor:.2f}")
last = table.capacityOutput:
size=4 capacity=8 load=0.50
size=7 capacity=16 load=0.44
size=13 capacity=32 load=0.41
size=25 capacity=64 load=0.39Two details matter here. The check uses "greater than", so a table at exactly 0.75 does not resize. And each resize roughly halves the load factor, which gives the table room to take about as many inserts again before the next resize.
Why doubling is cheap on average
A single resize costs O(n), because every entry moves. That sounds expensive, but resizes are rare. When the capacity doubles each time, the sizes at which resizes happen form a geometric series: about 8, 16, 32, and so on. The total number of entries moved over n insertions is bounded by a constant multiple of n. Spread across all insertions, each one pays an amortized O(1) cost, even though a few individual insertions are slow.
The growth factor is what makes this work. Compare doubling with growing by a fixed 8 buckets:
def total_moves(n, grow, capacity=8, max_load=0.75):
moves = 0
for size in range(1, n + 1):
if size / capacity > max_load:
moves += size # every entry is rehashed
capacity = grow(capacity)
return moves
print("doubling:", total_moves(100_000, lambda c: c * 2))
print("add 8: ", total_moves(100_000, lambda c: c + 8))For 100,000 inserts, doubling moves fewer than 300,000 entries in total, about 2 to 3 moves per insert. Adding a fixed 8 buckets triggers a resize every few inserts and moves hundreds of millions of entries. Multiplying the capacity by a constant factor is what keeps the total linear. Any factor above 1 works. Larger factors resize less often but waste more memory.
Edge cases
Tombstones count toward load
In an open-addressing table, a deleted slot holds a tombstone, and probes must walk past it. Lookups slow down because of occupied plus deleted slots, not live entries alone. This is why the probing table from the earlier chapter tracks _used (live entries plus tombstones) separately from _live, and checks _used against the limit. A table with many deletions can resize, or rebuild at the same capacity, to clear tombstones even when its live count is small.
Shrinking
Some libraries also shrink after many deletions. If the table doubles at α > 0.75 and halves at α < 0.375, the thresholds sit far apart. That gap prevents thrashing, where an insert and a delete alternate around a single boundary and each triggers a full rehash.
Latency spikes
Amortized O(1) describes the average. The one insertion that triggers a resize still takes O(n) time. In a latency-sensitive system, that pause can matter. Remedies include pre-sizing the table when you know the entry count, or using incremental rehashing, where the table migrates a few buckets per operation. Redis's dictionary does this.
Pre-sizing
If you know you will store about N entries, create the table with capacity at least N / max_load. This avoids every intermediate resize. Many libraries accept an initial capacity for this reason.
References held during a resize
Resizing moves entries to new storage. Any code that holds a position inside the old bucket array, such as an iterator, becomes invalid. Most libraries forbid modifying a table while iterating over it, and Python raises RuntimeError if a dict changes size during iteration.
Choosing a maximum load
| Goal | Direction |
|---|---|
| Fastest lookups, memory is cheap | Lower maximum load (0.5 or less) |
| Compact memory | Higher maximum load (0.75 to 0.9 with chaining) |
| Open addressing | Keep at or below about 0.5 to 0.7 |
| Fewer rehash pauses | Pre-size, or use a larger growth factor |
Exercise
A chained table starts with 8 buckets and a maximum load of 0.75. It resizes whenever the load factor exceeds 0.75 and doubles its capacity. On which insertion of a new distinct key does the first resize happen, and what is the capacity afterward?
Show answer
The 7th insertion. With 6 entries the load is 6/8 = 0.75, which does not exceed the limit. With 7 entries it is 7/8 = 0.875, which does. The table doubles to 16 buckets and rehashes all 7 entries.
Exercise
Why does growing the bucket array by a fixed number of buckets, such as 8, make n insertions cost O(n²) overall, while doubling keeps it O(n)?
Show answer
With a fixed increment, the number of resizes grows in proportion to n, and each resize moves a number of entries also proportional to n, so the total is quadratic. With doubling, resizes happen at geometrically spaced sizes, so the total entries moved form a series bounded by a constant times n.