Collisions, load factor and growing: why a dict is fast
🌍 In real life. Two letters for the same pigeonhole is no problem: the sorter stacks them, and finding one means checking a couple of envelopes. But at Eid the post office gets ten times the letters, and every pigeonhole fills into a tall pile. Now each search means digging. So the post office puts up a bigger wall with twice the pigeonholes and re-sorts every letter once. After that, piles are short again.
A hash table does the same: it keeps its buckets short by growing before they get crowded.
The idea in one sentence: a hash table keeps each bucket's chain of keys short by watching its load factor, keys ÷ buckets, and doubling the table when it gets too high.
Its words:
- chaining: a bucket holds a small list (a chain) of every key that landed there
- load factor: the number of keys divided by the number of buckets: the average chain length
- resize (or rehash): make a bigger table and place every key again, because the remainder changes
How it works, step by step:
- put: work out the bucket; compare the key with each key in that chain; add it if it isn't there
- if the table is now more than 3/4 full, make one twice as big and put every key in again
- find: work out the bucket; compare with the keys in that chain only
Watch "bee" collide with "cat" and "fox" with "cow", then the table double and split both pairs.
Why it is correct. After a resize every key is placed with the new size, and find also uses the new size, so they still agree. Keys that shared a bucket often split up, because the remainder by 8 can differ where the remainder by 4 was equal (300 % 4 = 0 but 300 % 8 = 4).
What it costs, worked out:
- a put or find compares with one chain, and the average chain is the load factor, at most 3/4: O(1) on average
- the worst case is every key in one bucket: then the table is just a list, O(n). A good hash function makes that very unlikely
- a resize copies every key, O(n), but it only happens each time the size doubles, so, like
list.appendin Chapter 34, the cost shared over all puts is amortised O(1)
Python's dict follows the same plan with a cleverer layout (no chains: a full slot sends the key to another slot), grows when about 2/3 full, and also remembers the order keys were added.
def bucket(key, size):
return sum(ord(c) for c in key) % size
class HashTable:
def __init__(self, size=4):
self.buckets = [[] for _ in range(size)]
self.count = 0
def put(self, key):
chain = self.buckets[bucket(key, len(self.buckets))]
if key not in chain:
chain.append(key)
self.count += 1
if self.count * 4 > len(self.buckets) * 3:
self.grow()
def grow(self):
old = self.buckets
self.buckets = [[] for _ in range(2 * len(old))]
for chain in old:
for key in chain:
self.buckets[bucket(key, len(self.buckets))].append(key)
table = HashTable()
for word in ["cat", "bee", "cow", "fox", "ant"]:
table.put(word)
print(len(table.buckets), table.buckets)Mistakes and edge cases. d[key] on a missing key raises KeyError: use d.get(key, default) or check key in d first (also O(1)). And never add or remove keys while looping over a dict: changing the number of keys in the middle could move them about under the loop, so Python stops you with RuntimeError: dictionary changed size during iteration. Loop over list(d) instead.
Quiz
A table has 8 buckets and 6 keys. What is its load factor?
print(6 / 8)Why does a key sometimes change bucket when the table doubles?
- The bucket is the remainder after dividing by the size, and the size changed
- The key's hash changes when it is copied
- Keys are sorted during a resize
When is looking up a key in a hash table O(n)?
- When almost every key lands in the same bucket
- Always: it has to check every key
- Never: it is always exactly one step
What does this print?
stock = {"rice": 10, "dal": 4} print(stock.get("oil", 0), "dal" in stock)Which line causes the RuntimeError? (Python reports it at the for line, the next time the loop asks for a key.)
marks = {"Mina": 80, "Rafi": 35, "Tara": 50} for name in marks: if marks[name] < 40: del marks[name] print(marks)
Coding tasks
Build a hash map: finish
HashMap, which stores key → value pairs.self.bucketsis a list of buckets; each bucket is a list of[key, value]pairs, and a key's bucket isbucket(key, len(self.buckets)).put(key, value)adds the pair, or changes the value if the key is already there; when more than 3/4 full it doubles its buckets and places every pair again.get(key)gives the value, orNone.len()is the number of keys.Write
chain_lengths(keys, size): how many keys land in each ofsizebuckets with the letter-sum hash, as a list. Then the longest chain ismax(...), and the load factor islen(keys) / size.