Sub topic 8
Chained Hash Tables and the Load Factor
This chapter assumes you know Big-O notation, how fixed-size arrays are allocated and indexed, and what a hash function does. It also assumes you can read short Python programs. Here we build a chained hash table, work out what a lookup costs, and see why one number, the load factor, controls that cost. Resizing the table to keep that number in check is the topic of the next chapter.
What a chained hash table is
A hash table stores key-value pairs so that lookup, insertion and deletion are fast on average. It keeps an array of buckets. A hash function maps each key to an integer, and the table reduces that integer modulo the bucket count to pick a bucket index.
Two different keys can land in the same bucket. This is a collision. Collisions cannot be avoided in general: if you store more keys than there are buckets, at least two keys must share one. Chaining is the simplest way to handle them. Each bucket holds a small list (the chain) of every pair whose key maps to that bucket.
The three operations all follow the same pattern:
- Compute the bucket index from the key.
- Scan the chain in that bucket, comparing keys.
- Act on the result. Return the value, replace it, append a new pair, or remove a pair.
Step 1 takes constant time. Step 2 takes time proportional to the chain length. Everything interesting about the cost comes from that chain length.
Defining the load factor
Let n be the number of stored entries and m the number of buckets. The load factor is
α = n / m
It is the average chain length. A table with 1,000 entries in 500 buckets has α = 2, so a typical chain holds two entries. Unlike open addressing, chaining lets α exceed 1, because a bucket can hold any number of entries.
The load factor is the control knob of a hash table. A low α wastes memory on empty buckets. A high α makes chains long and operations slow. Implementations pick a maximum load factor and resize before α passes it.
The cost of one operation
Everything below rests on one modelling assumption, called simple uniform hashing. Each key is equally likely to hash to any of the m buckets, independently of the other keys. Real hash functions only approximate this, and the failure cases are covered later in this chapter.
Under that assumption, with n entries in m buckets:
- Unsuccessful lookup (key absent). The scan reaches the end of the chain. The chain the key hashes to has expected length α, so the expected cost is Θ(1 + α). The "1" is the hashing and indexing work.
- Successful lookup (key present). The scan stops at the target. The entries ahead of it are the ones appended earlier to the same bucket, which is about α/2 on average. The expected number of comparisons is about 1 + α/2, so the cost is also Θ(1 + α).
- Insertion. To avoid duplicate keys, the table first searches the chain, which costs Θ(1 + α). If it knows the key is new, appending is O(1).
- Deletion. This is a search followed by removing the entry from the chain, so it costs Θ(1 + α).
The key point is that every operation is Θ(1 + α) in expectation. If α is bounded by a constant, such as 0.75, each operation takes constant expected time. If α grows, the cost grows with it.
Why a fixed bucket count fails
Suppose the table never changes m. Then α = n/m grows linearly with n, and the cost Θ(1 + n/m) becomes Θ(n) for large n, because m is a constant. A table with 64 buckets holding a million entries has chains of about 15,600 entries. It behaves like 64 linked lists, and the hash table has lost its advantage.
The fix is to grow m in proportion to n, so that α stays below a constant. That means occasionally allocating a bigger bucket array and moving every entry into it. That move is expensive, and it is exactly the kind of cost that amortised analysis handles. The next chapter does this analysis. This chapter only needs the conclusion: bounding α is what makes the per-operation cost constant.
Measuring chain length
The program below builds a chained table with a fixed number of buckets, fills it to several load factors, and measures key comparisons. It does not resize, so you can watch α rise.
import random
class ChainedTable:
def __init__(self, bucket_count):
self.buckets = [[] for _ in range(bucket_count)]
self.size = 0
def _bucket(self, key):
return self.buckets[hash(key) % len(self.buckets)]
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
def comparisons(self, key):
"""Number of key comparisons a lookup for `key` performs."""
count = 0
for k, _ in self._bucket(key):
count += 1
if k == key:
break
return count
@property
def load_factor(self):
return self.size / len(self.buckets)
def longest_chain(self):
return max(len(b) for b in self.buckets)
rng = random.Random(7)
BUCKETS = 1024
print("alpha hit_cmp 1+a/2 miss_cmp longest")
for n in (256, 1024, 4096, 16384):
table = ChainedTable(BUCKETS)
present = rng.sample(range(10**9), n)
for key in present:
table.put(key, key)
hit = sum(table.comparisons(k) for k in present) / n
absent = rng.sample(range(10**9, 2 * 10**9), 2000)
miss = sum(table.comparisons(k) for k in absent) / len(absent)
alpha = table.load_factor
print(f"{alpha:5.2f} {hit:8.2f} {1 + alpha / 2:5.2f} {miss:8.2f} {table.longest_chain():7d}")The hit_cmp column should track 1 + α/2, and miss_cmp should track α. The exact figures depend on the random keys, so expect small differences. The longest chain is noticeably bigger than the average, and it grows with α. At α = 16 the average successful lookup makes about 9 comparisons, and the worst bucket may hold 30 entries or more. Averages describe typical operations, not the unluckiest one.
Choosing a maximum load factor
Every implementation fixes a threshold, and the choice trades memory against speed.
| Maximum α | Memory use | Expected chain scan | Resize frequency |
|---|---|---|---|
| 0.5 | Many empty buckets | Very short | Higher |
| 0.75 | Moderate | Short | Moderate |
| 1.0 | About one entry per bucket | About 1.5 comparisons for a hit | Lower |
| 2.0 or more | Compact | Noticeably longer chains | Lowest |
A threshold of 0.75 is a common default. Java's HashMap uses it. A higher threshold saves memory and resizes less often, but every lookup scans more entries. A lower threshold does the opposite. Any constant threshold gives O(1) expected operations, so the choice is about constant factors, not asymptotics.
Memory per entry also matters. Each chained entry usually carries a pointer or object header on top of the key and value, and each empty bucket still occupies a slot in the array. Chains of linked nodes also scatter entries across memory, which hurts CPU cache behaviour compared with a contiguous array.
Where the model breaks
Simple uniform hashing is an assumption, and several things can violate it.
- A weak hash function. If many keys share low-order patterns, such as multiples of 1024 with a power-of-two bucket count, they all hit the same bucket. The table degrades toward a single list with Θ(n) operations, even though α is small.
- Adversarial keys. An attacker who knows the hash function can craft keys that all collide. This is a real denial-of-service technique against web servers that hash request parameters. The usual defence is a randomly seeded hash function. Python randomises
strandbyteshashes per process for this reason. - Poor key equality. If comparing keys is expensive, such as long strings with a shared prefix, each chain step costs more than O(1).
- Worst case. Even with a good hash function, the worst case for a single operation is Θ(n), because all
nkeys could collide. Expected O(1) is a statement about the average, not a ceiling. Some implementations cap the damage. Java 8'sHashMapconverts a long chain into a balanced tree, which bounds that bucket's lookups at O(log n).
What to carry forward
- A chained table costs Θ(1 + α) per operation in expectation, where α = n/m.
- With a fixed bucket count, α grows with
n, so operations degrade to Θ(n). - Keeping α below a constant makes the expected cost constant. Doing that requires resizing, whose own cost is the subject of the next chapter.
- The guarantee relies on well-spread hashes and is about expectation, not the worst single operation.
Exercise
A chained table has 200 buckets and holds 500 entries, and the hash function spreads keys uniformly. What is the load factor? About how many key comparisons does a lookup for an absent key make, and about how many does a lookup for a present key make?
Show answer
α = 500 / 200 = 2.5. An absent key scans a whole chain of expected length α, so about 2.5 comparisons. A present key needs about 1 + α/2 = 2.25 comparisons.
Exercise
You keep a table at a fixed 1,024 buckets and insert keys without ever resizing. Explain why the expected cost per operation is not O(1), and state what the cost becomes when n is very large.
Show answer
The expected cost is Θ(1 + n/1024). With m fixed at 1,024, α = n/1024 grows in proportion to n, so chains lengthen without bound. For large n the cost is Θ(n), because 1,024 is a constant factor.
Exercise
A table keeps α below 0.75, yet lookups are slow, and a profiler shows one bucket holding 40% of all entries. Which assumption has failed, and does the load factor explain the slowdown?
Show answer
Simple uniform hashing has failed: the keys are not spreading evenly across buckets. The load factor does not explain it, because α is only the average chain length. It stays small while one chain grows very long. The fix is a better or randomly seeded hash function, or a tree-based fallback for long chains.