Sub topic 3
Collision handling with chaining
This chapter assumes you know what a hash table does, can read simple Python, and know Big-O basics. The previous chapter explained why collisions are unavoidable. This one covers the most common way to handle them.
The idea
Separate chaining makes each bucket hold a small collection of entries instead of a single entry. Python code usually uses a list. Some other implementations use a linked list. When two keys hash to the same index, both entries go into that bucket's chain.
Every operation starts the same way: compute hash(key) % capacity to find the bucket. After that, the operation scans the chain.
A minimal implementation
This version has no resizing yet, so you can watch chains grow.
class ChainedTable:
def __init__(self, capacity=4):
self._buckets = [[] for _ in range(capacity)]
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 get(self, key, default=None):
for k, v in self._bucket(key):
if k == key:
return v
return default
def delete(self, key):
bucket = self._bucket(key)
for i, (k, _) in enumerate(bucket):
if k == key:
del bucket[i]
self._size -= 1
return True
return False
def chain_lengths(self):
return [len(b) for b in self._buckets]
table = ChainedTable()
for key in range(10):
table.put(key, str(key))
print(table.chain_lengths())
print(table._size / len(table._buckets))The output is [3, 3, 2, 2] and 2.5. Ten entries share four buckets, so the average chain holds 2.5 entries.
What each operation costs
Each operation costs the length of one chain.
- Get: scan the chain until the key matches or the chain ends.
- Put: scan the chain first, because the key may already exist. Then either replace the value or append.
- Delete: scan the chain, then remove the entry. Chaining needs no special marker for deleted entries, which makes it simpler than open addressing here.
Chain length therefore sets the cost. With a good hash function, entries spread evenly and the average chain length equals the load factor, which is size divided by capacity. The standard estimates are load entries examined for a missing key and 1 + load / 2 for a key that is present. At a load factor of 0.75, a missing key costs about 0.75 comparisons and a present key about 1.4.
Load factor can exceed 1
The demo above has a load factor of 2.5, and it still works. Chains just get longer. Open addressing cannot do this, because every entry needs its own slot. This is why chaining degrades gradually as the table fills, while linear probing degrades sharply near a load factor of 1.
The worst case
The averages assume the hash function spreads keys evenly. If many keys land in one bucket, one chain does most of the work:
bad = ChainedTable()
for key in (0, 4, 8, 12, 16):
bad.put(key, key)
print(bad.chain_lengths())This prints [5, 0, 0, 0]. The load factor is 1.25, but every lookup scans the one long chain. In the extreme, all n keys share a bucket and each operation costs O(n). Load factor describes the average only, so a poor hash function or adversarial keys can defeat it. Resizing helps with the average but cannot fix a hash function that sends keys to the same place.
Trade-offs of chaining
- Strength: it tolerates high load factors and handles deletion simply.
- Cost: each entry carries extra overhead for a list or node. Following links also scatters memory accesses, which is slower on a CPU cache than scanning a contiguous array.
- Consequence for resizing: chaining can run at a higher load factor than open addressing before lookups become slow. That is why chaining tables often use thresholds near 0.75 or higher. Later chapters cover how to choose one.
Exercise
A chained table has 16 buckets and holds 20 entries. What is its load factor, and about how many entries does an unsuccessful lookup examine if keys are spread evenly? Can a bad hash function make the cost worse?
Show answer
The load factor is 20 / 16 = 1.25. An unsuccessful lookup examines about 1.25 entries on average. Yes. If many keys hash to the same bucket, one chain gets long and lookups in it can cost up to O(n), even though the load factor is unchanged.