Sub topic 6
Resolving Collisions with Chaining
This chapter assumes you know Python classes and lists, the modulo operator, and introductory Big-O. It also assumes you have seen that two different keys can map to the same bucket index, which is a collision. Here you will see the most direct way to handle one: let each bucket hold more than one entry.
The idea
In separate chaining, each bucket holds a small collection of key-value pairs, called a chain. A collision is no longer a problem. If two keys land in the same bucket, both pairs go into that bucket's chain.
Every operation then has the same shape:
- Hash the key and reduce it to a bucket index.
- Scan only that bucket's chain, comparing keys with
==. - Act on the match, or on the end of the chain.
The diagram shows a table with 4 buckets and 5 entries. Buckets 0 and 2 hold chains of length 2.
The chain can be a Python list, a linked list, or a tree. Lists are the simplest and are usually fast for short chains, because the data sits together in memory. This chapter uses lists.
A complete implementation
class ChainedHashTable:
def __init__(self, capacity=8, max_load=0.75):
self._buckets = [[] for _ in range(capacity)]
self._size = 0
self._max_load = max_load
def _index(self, key):
return hash(key) % len(self._buckets)
def put(self, key, value):
bucket = self._buckets[self._index(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(len(self._buckets) * 2)
def get(self, key, default=None):
for k, v in self._buckets[self._index(key)]:
if k == key:
return v
return default
def remove(self, key):
bucket = self._buckets[self._index(key)]
for i, (k, _) in enumerate(bucket):
if k == key:
del bucket[i]
self._size -= 1
return True
return False
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[self._index(k)].append((k, v))
table = ChainedHashTable()
for i in range(20):
table.put(f"key{i}", i)
print(table.get("key7"))
print(table.remove("key7"), table.get("key7"))This prints 7, then True None.
How each operation works
put has two outcomes. If the key is already in the chain, it replaces the pair and leaves _size unchanged, because the number of entries did not grow. If the key is absent, it appends the pair, increments _size, and checks the load factor.
get computes the same index that put used and scans that one chain. It never looks at other buckets, so the work depends on the chain length and not on the table size.
remove is easy compared with open addressing. Deleting a pair from a list does not affect any other key's position, so no tombstone markers are needed.
What `_resize` does
_resize calls _index again for every pair. It does not copy the old buckets across. The index is hash(key) % len(self._buckets), so when the bucket count changes, most keys belong in different buckets. Copying chains unchanged would make get search the wrong place and report missing keys.
Load factor and chain length
The load factor is the number of entries divided by the number of buckets. We write it as α = n / m. With chaining, α can exceed 1, because a chain can hold any number of entries. That is one difference from open addressing, where α cannot exceed 1.
If the hash function spreads keys evenly, the average chain length is α. This gives the usual cost estimates:
| Operation | Expected pairs compared | At α = 0.75 |
|---|---|---|
| Lookup of a key that is present | about 1 + α/2 | about 1.4 |
| Lookup of a key that is absent | about α | about 0.75 |
| Insert of a new key | about α, then append | about 0.75 |
These figures assume uniform hashing, meaning each key is equally likely to land in any bucket. Real hash functions only approximate this.
The code keeps α at or below 0.75 by doubling the bucket count when α passes max_load. Doubling costs O(n) for that one insert. Because each resize doubles the capacity, the total resize work over n inserts stays proportional to n, so the amortized cost per insert is O(1).
Seeing the effect of a poor hash
Chaining stays fast only if chains stay short, and that depends on the hash function. The snippet below uses 12 keys and 16 buckets. It compares the polynomial hash with a poor hash that uses only the key's length.
def string_hash(s, size):
h = 0
for ch in s:
h = (h * 31 + ord(ch)) % size
return h
def length_hash(s, size):
return len(s) % size
def max_chain(hash_fn, keys, size):
counts = [0] * size
for k in keys:
counts[hash_fn(k, size)] += 1
return max(counts)
keys = [f"key{i}" for i in range(12)]
print(max_chain(string_hash, keys, 16))
print(max_chain(length_hash, keys, 16))The output is 1 and then 10. The length-based hash puts ten keys in one bucket, because key0 through key9 all have length 4. Every lookup of those keys scans a list of ten pairs. In the extreme case, every key lands in one bucket and the table becomes a list with O(n) operations.
Common errors
- Changing a key after insertion. If a key's hash changes,
getcomputes a different index and cannot find the pair. Use immutable keys, or never change fields that take part inhashand==. - Defining
__eq__without a matching__hash__. Equal keys must have equal hashes. If they do not, equal keys land in different buckets and are treated as separate entries. - Updating
_sizeon an overwrite. An overwrite must leave the count unchanged. Otherwise the load factor drifts upward and the table resizes too often. - Resizing while iterating over the buckets. The loop in
_resizereads fromold, so it is safe. A loop that walksself._bucketswhile callingputcan skip or repeat entries. - Treating
Noneas "missing".getreturnsNonefor absent keys, so a storedNonelooks the same. Pass a unique sentinel asdefaultwhen this matters.
Design choices for the chain
| Chain type | Strengths | Weaknesses |
|---|---|---|
| Python list of pairs | Simple, compact, good cache behavior | Delete shifts later items; scan is O(chain length) |
| Linked list | Constant-time delete once the node is found; no shifting | Extra pointer per entry; poor cache behavior |
| Balanced tree | Worst-case chain cost drops from O(n) to O(log n) | More code; keys must be orderable or hashes comparable |
Some production libraries combine these. Java's HashMap uses chains by default, and it converts a bucket to a tree when the chain grows long (8 entries, once the table has at least 64 buckets). Its default maximum load factor is 0.75, the same as in our code. This limits the damage from deliberately colliding keys. Python's built-in dict does not use chaining. It uses open addressing, which the next chapter covers.
Chaining also has costs. Each entry needs a container slot and often a pair object, so memory use is higher than in a flat array of slots. Empty buckets still take space. Following references between pairs can be slower on modern CPUs than scanning contiguous slots.
Summary of trade-offs
Chaining is easy to implement and tolerates load factors above 1. Deletion is trivial. Performance degrades smoothly as α rises. Its weaknesses are extra memory per entry, weaker cache behavior with linked chains, and a worst case of O(n) when many keys share a bucket.
Exercise
A ChainedHashTable has 16 buckets and max_load of 0.75. It currently holds 12 distinct keys. You call put with a new key, then put again with the same key and a different value. How many buckets does the table have afterward, and what is the size?
Show answer
The first put raises the size to 13, and 13 / 16 = 0.8125 exceeds 0.75, so the table doubles to 32 buckets and rehashes all 13 entries. The second put finds the key in its chain and replaces the value, so the size stays at 13 and no resize occurs. Final state: 32 buckets, size 13.
Exercise
A teammate changes _resize so that it moves each old bucket into the same index of the larger array instead of calling _index for every pair. Why will get fail for some keys afterward?
Show answer
_index computes hash(key) % len(self._buckets). After the table doubles, the modulus changes, so a key's correct index is usually different from its old index. A key left in its old bucket is not in the chain that get scans for it, so get returns the default even though the key is stored.