Sub topic 9
Load Factor and Resizing
This chapter assumes you know how a hash table maps a key to a bucket with hash(key) % bucket_count, and that collisions are handled by chaining or open addressing. It also assumes basic Big-O notation. Here you will see why a table must grow as it fills, and how growing keeps lookups fast.
Why a fixed bucket count fails
The ChainedMap from the earlier chapter starts with 8 buckets and never changes that number. With 8 entries, buckets are short and lookups are quick. With 80,000 entries, each bucket holds about 10,000 pairs, and every get scans a long list. Lookup time becomes proportional to the number of entries, which is O(n). The table behaves like a list.
The cause is the ratio of entries to buckets. That ratio has a name.
Load factor
The load factor is the number of stored entries divided by the number of buckets.
load factor = entries / bucketsWith 6 entries in 8 buckets, the load factor is 0.75. With chaining, the load factor is the average bucket length, so it directly sets the expected cost of a lookup. With open addressing, each bucket holds at most one entry, so the load factor cannot exceed 1. Probe sequences grow quickly as it approaches 1.
Implementations choose a maximum load factor and resize when they pass it. Java's HashMap uses 0.75 by default. CPython's dict resizes when about two thirds of its slots are used. These are tuning choices, not laws. A lower limit uses more memory and gives shorter probes. A higher limit saves memory and slows lookups.
Resizing and rehashing
When the load factor passes the limit, the table allocates a larger bucket array, usually twice the size. It then moves every entry into the new array.
Entries cannot simply be copied to the same index. The index is hash(key) % bucket_count, and bucket_count has changed, so most entries belong in a different bucket. Each key must be placed again. This step is called rehashing.
The following code adds resizing to the earlier map.
class ResizingMap:
MAX_LOAD = 0.75
def __init__(self, bucket_count=4):
self._buckets = [[] for _ in range(bucket_count)]
self._size = 0
def _bucket(self, key):
return self._buckets[hash(key) % len(self._buckets)]
def _resize(self):
old_buckets = self._buckets
self._buckets = [[] for _ in range(len(old_buckets) * 2)]
for bucket in old_buckets:
for key, value in bucket:
self._buckets[hash(key) % len(self._buckets)].append((key, value))
def put(self, key, value):
bucket = self._bucket(key)
for i, (k, _) in enumerate(bucket):
if k == key:
bucket[i] = (key, value)
return
bucket.append((key, value))
self._size += 1
if self._size / len(self._buckets) > self.MAX_LOAD:
self._resize()
def get(self, key, default=None):
for k, v in self._bucket(key):
if k == key:
return v
return default
m = ResizingMap()
for n in range(100):
m.put(n, n * n)
print(len(m._buckets), m.get(7), m.get(99), m.get(500)) # 256 49 9801 NoneThe table starts with 4 buckets and doubles whenever the load factor exceeds 0.75. After 100 insertions it has 256 buckets, so the load factor stays below 0.75 and buckets stay short.
Why doubling keeps inserts cheap on average
One resize costs O(n), because every entry is moved. If the table grew by a fixed amount, such as 10 buckets, resizes would be frequent and the total cost of n inserts would be O(n²). Doubling makes resizes rare. The sizes you copy form a series like 1, 2, 4, 8, up to n, which sums to less than 2n. Spread across n inserts, that is a constant amount of extra work per insert. This is called amortized O(1).
Amortized means the average over many operations. A single insert can still be slow. In latency-sensitive code, one insert that triggers a resize of a million entries can cause a visible pause.
Common errors
- Assuming a table never slows down. A table that never resizes degrades toward O(n) lookups.
- Forgetting to rehash. Copying entries to the same index in the new array makes later lookups miss, because
hash(key) % new_countpoints somewhere else. - Treating bucket positions as stable. Resizing changes where entries live, which is one reason iteration order is not something to rely on.
Exercise
A chained table has 16 buckets and holds 12 entries, with a maximum load factor of 0.75. What is its load factor, and what happens when you insert one more new key?
Show answer
The load factor is 12 / 16 = 0.75, which does not exceed the limit. After the insert there are 13 entries, so the load factor is 13 / 16 = 0.8125, above 0.75. The table allocates 32 buckets and rehashes all 13 entries, because the index depends on the bucket count. The load factor then drops to 13 / 32, about 0.41.