Sub topic 4
Separate Chaining: A Collection Per Slot
This chapter assumes you know arrays and indexing, basic Python classes and tuples, modulo arithmetic, and Big-O notation with average versus worst-case cost. You have seen that two keys can hash to the same slot. Separate chaining is the first strategy for handling that.
The idea
In separate chaining, each slot of the table holds a collection of entries instead of a single entry. This chapter uses a Python list of (key, value) pairs. This collection is called a bucket. When two keys land in the same slot, both pairs go into that slot's bucket.
Every operation follows the same three steps:
- Hash the key and reduce it with modulo to pick a slot index.
- Scan that slot's bucket for the key.
- Act on the result: replace, append, return, or delete.
A working implementation
class ChainedHashMap:
def __init__(self, capacity=8):
self._buckets = [[] for _ in range(capacity)]
self._size = 0
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) > 1.0:
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))Some details are worth noting:
putscans the bucket first. If the key already exists, it replaces the pair. Skipping this check would create duplicate keys._sizecounts all stored pairs, not occupied slots. This is what the load factor needs.- Removal is simple. You delete the pair from the list. No placeholder is needed, unlike open addressing, which needs tombstones.
_resizerecomputes every index, becausehash(key) % capacitychanges when the capacity changes. Copying buckets unchanged would make keys unreachable.
Cost
Let n be the number of stored pairs and m the number of slots. The load factor is n / m, which is the average bucket length. With a well-spread hash function, a lookup costs one hash plus a scan of about n / m entries. This implementation doubles the table when the load factor passes 1.0, so the average scan stays short and operations are O(1) on average.
The worst case is different. If every key lands in one bucket, the table behaves like one list, and lookup costs O(n). This happens with a poor hash function or with keys chosen to collide on purpose.
Common errors
- Forgetting to check for an existing key in
put. The map then holds two entries for one key, andgetreturns the older one. - Using a mutable or unstable key. If a key's hash changes after insertion, the pair sits in the wrong bucket and
getcannot find it. Python lists are unhashable for this reason. - Resizing without rehashing. Slot indexes depend on capacity, so every pair must be reinserted.
- Measuring load factor by occupied slots. Count pairs, not non-empty buckets.
Exercise
A ChainedHashMap has 8 slots and holds 12 pairs, and the resize check has not run. What is its load factor, and what is the expected number of pairs scanned in a bucket on a lookup, assuming keys are spread evenly?
Show answer
The load factor is 12 / 8 = 1.5. With even spread, the average bucket holds 1.5 pairs, so a lookup scans about 1.5 pairs.
Exercise
Why must _resize recompute self._index(k) for each pair instead of moving whole buckets to the same position in the new table?
Show answer
The index is hash(key) % len(buckets). When the capacity changes, the result of the modulo changes. A pair left at its old position may no longer be in the bucket that get searches, so the key would appear missing.