Sub topic 8
Chained Hash Tables and the Load Factor
This chapter assumes you know Big-O notation, how fixed-size arrays are indexed, what a hash function does, and how to read short Python programs. It sets up the cost model that the later chapter on resizing relies on.
How chaining works
A chained hash table keeps a fixed-size array of buckets. Each bucket holds a list, called a chain, of the key-value pairs whose keys hash to that bucket. To find the bucket for a key, compute hash(key) % number_of_buckets.
Two keys that land in the same bucket have collided. Chaining resolves a collision by appending to the chain. Every operation follows the same three steps:
- Hash the key to pick a bucket.
- Scan that bucket's chain for an equal key.
- Read, overwrite or append, depending on the operation.
Step 1 costs O(1). Step 2 costs time proportional to the chain length. The cost of the whole table therefore depends on how long the chains are.
The load factor
The load factor, written α, is the number of stored entries divided by the number of buckets:
α = n / m
With 6 entries in 8 buckets, α = 0.75. If the hash function spreads keys evenly, the average chain holds α entries. Under the usual simple uniform hashing assumption, each key is equally likely to land in any bucket, independently of the others. The expected costs are then:
| Operation | Expected comparisons in the chain |
|---|---|
| Unsuccessful lookup (key absent) | about α |
| Successful lookup (key present) | about 1 + α/2 |
| Insert (must check for an existing key first) | about α, plus O(1) to append |
So each operation costs O(1 + α) in expectation. If α stays below a constant such as 0.75, every operation is O(1) in expectation. If the bucket count never changes, α equals n/m and grows without bound as you insert, and operations degrade toward O(n).
Measuring it
This program uses a table with a fixed number of buckets and records the load factor, the longest chain, and the average number of comparisons for a successful lookup. The keys are seeded random integers, so the output is repeatable.
import random
class FixedChainedTable:
def __init__(self, bucket_count):
self._buckets = [[] for _ in range(bucket_count)]
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
def load_factor(self):
return self._size / len(self._buckets)
def longest_chain(self):
return max(len(b) for b in self._buckets)
def avg_comparisons(self):
total = sum(sum(range(1, len(b) + 1)) for b in self._buckets)
return total / self._size
rng = random.Random(1)
for n in (100, 1000, 10000):
table = FixedChainedTable(100)
for _ in range(n):
k = rng.getrandbits(64)
table.put(k, k)
print(n, table.load_factor(), table.longest_chain(),
round(table.avg_comparisons(), 1))The bucket count stays at 100, so α rises from 1 to 10 to 100. The average comparisons per successful lookup rise with it, close to 1 + α/2. The cost grows linearly with n, which is the behaviour the next chapters fix.
Why the load factor needs a limit
The load factor is the one number you can control. A table that keeps α below a fixed maximum, often between 0.5 and 1, keeps chains short. The cost of that policy is a resize, which means allocating more buckets and moving every entry. Because the bucket index depends on the bucket count, you must rehash every key, not just copy it.
Common errors
- Reading "O(1)" as a worst-case guarantee. Chaining gives O(1) in expectation, and only if α is bounded.
- Forgetting that
putmust scan the chain for an existing key. Without that scan, duplicate keys appear. - Comparing α across tables with different chain structures. Linked lists, arrays and trees as chains have different constants, though the O(1 + α) shape is the same.
Exercise
A chained hash table has 64 buckets and holds 112 entries. What is the load factor, and roughly how many comparisons does an unsuccessful lookup need in expectation, assuming uniform hashing?
Show answer
α = 112 / 64 = 1.75. An unsuccessful lookup scans a whole chain, which has about α = 1.75 entries on average, so it needs about 1.75 comparisons.