Sub topic 6
Resolving collisions with chaining
This chapter assumes you know how a hash function produces an integer and how hash(key) % size selects a bucket index. It also assumes you know that two different keys can land in the same bucket. Here you will see the most direct fix for that: separate chaining.
The idea
In separate chaining, each bucket holds a small collection of entries instead of a single entry. Python's built-in list works well for this. Keys that collide share a bucket, and the table searches only that bucket.
Every operation follows the same two steps:
- Hash the key and reduce it to a bucket index.
- Scan the bucket's entries, comparing keys with
==.
The hash narrows the search to one bucket. Equality then finds the exact key within it.
A working implementation
The class below stores (key, value) pairs in each bucket's list.
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"))The program prints 7, then True None.
How each operation works
putscans the chain first. If the key exists, it replaces the value, so a key never appears twice. Otherwise it appends a new pair and increments_size.getscans one chain and returns the value, or the default if no key matches.removedeletes the pair from the chain. Deletion is simple here, because removing an entry never affects where other keys live._resizerebuilds the table with more buckets. It recomputes every index, becausehash(key) % len(buckets)changes when the length changes. Copying entries to their old positions would make them unreachable.
Why the load factor matters
The load factor is the number of entries divided by the number of buckets. It is also the average chain length. At 0.75, a typical chain holds less than one entry, so scans are short. If the table never grew, chains would lengthen with every insertion and each lookup would drift toward a linear scan.
Doubling the bucket count when the load factor passes 0.75 keeps the average chain short. Doubling also spreads the cost of rebuilding over many insertions.
Common errors
- Reusing old indexes after a resize, which makes keys appear to vanish.
- Appending without checking for an existing key, which leaves stale duplicate values.
- Mutating a key after inserting it. Its hash changes, and the table searches the wrong bucket.
Exercise
A chained table has 16 buckets and holds 12 entries. What is its load factor, and does a 13th insertion with max_load=0.75 trigger a resize?
Show answer
The load factor is 12 / 16 = 0.75. After the 13th insertion it is 13 / 16 = 0.8125, which exceeds 0.75, so the table doubles to 32 buckets and re-places every entry.