Separate chaining
Separate chaining handles collisions by hanging a list, a bucket, off each slot and putting every key that lands there into it; deleting needs no tombstone, and once the load factor passes 1 the buckets double and every key is rehashed.
Open addressing needs tombstones, has to grow at 2/3 full, and clusters. The other way is much simpler: hang a list off every slot (a bucket), and every key that lands on the slot goes into that bucket; a collision never takes anybody else's slot. Java's HashMap works this way: 16 buckets by default, doubling once the keys outnumber 0.75 times the buckets; so does C++'s unordered_map. This lesson uses Python lists as buckets and writes a complete separate-chaining hash table by hand.
Each bucket is a list
Table size 11: key k goes into bucket k % 11, after whatever is already there. The same 8 keys as last lesson:
1m = 112buckets = [[] for _ in range(m)]3 4for k in [22, 41, 53, 46, 30, 13, 1, 67]:5 buckets[k % m].append(k)6 7for i, b in enumerate(buckets):8 if b:9 print(i, b)10 11def find(k):12 compares = 013 for x in buckets[k % m]:14 compares += 115 if x == k:16 return True, compares17 return False, compares18 19print(find(30), find(19), find(5))
0 [22] 1 [1, 67] 2 [46, 13] 8 [41, 30] 9 [53] (True, 2) (False, 2) (False, 0)
[[] for _ in range(m)] must not be written [[]] * m: that is m names pointing at one list (the trap from the "names and objects" lesson), and every key would end up in the same bucket.
This stage's 8 keys 22 41 53 46 30 13 1 67 are appended to their buckets in turn. How many comparisons does finding 13 take?
[46, 13]: 46 went in first and sits in front, so 13 is reached on the 2nd comparison.Make the buckets with [[]] * m, then put a 7 into bucket 1. What does it print?
1m = 32buckets = [[]] * m3buckets[1].append(7)4print(buckets)
[[]] * m is 3 names pointing at the same list. Appending to "bucket 1" makes all 3 buckets seem to gain a 7. That is why the buckets are made one by one with [[] for _ in range(m)].A complete hash table
To store keys and values, a bucket holds small lists like [key, value]. The bucket is hash(key) % m, so any hashable key works (a string's bucket number changes from run to run, but what get returns never does):
1class HashTable:2 def __init__(self, m=8):3 self.buckets = [[] for _ in range(m)]4 self.n = 05 6 def _bucket(self, key):7 return self.buckets[hash(key) % len(self.buckets)]8 9 def put(self, key, value):10 b = self._bucket(key)11 for pair in b:12 if pair[0] == key: # the key is already here: change the value only13 pair[1] = value14 return15 b.append([key, value])16 self.n += 117 18 def get(self, key, default=None):19 for k, v in self._bucket(key):20 if k == key:21 return v22 return default23 24 def delete(self, key):25 b = self._bucket(key)26 for i in range(len(b)):27 if b[i][0] == key:28 b.pop(i)29 self.n -= 130 return True31 return False32 33 def __len__(self):34 return self.n35 36t = HashTable()37t.put("apple", 3)38t.put("pear", 5)39t.put("apple", 4)40print(len(t), t.get("apple"), t.get("kiwi"), t.get("kiwi", 0))41print(t.delete("pear"), t.delete("pear"), len(t))
2 4 None 0 True False 1
put searches the bucket first: if the key is there, only the value changes and the count stays; dict's d[k] = v behaves the same. __len__ makes len(t) work; it returns the stored n, O(1), without counting every bucket.
Deleting just takes the pair out of the bucket's list, with no tombstone: finding only walks its own bucket, so nobody else's path breaks when one key goes.
Order inside a bucket doesn't matter, so b.pop(i) can also be "cover slot i with the last one, then pop()", which moves nothing: b[i] = b[-1]; b.pop().
Five keys into four buckets. What does it print?
1m = 42buckets = [[] for _ in range(m)]3for k in [5, 9, 2, 13, 6]:4 buckets[k % m].append(k)5print(buckets[1], max(len(b) for b in buckets))
Pick one for the blank so that a key that is already there only gets its value changed, without adding another pair.
1m = 42buckets = [[] for _ in range(m)]3 4def put(key, value):5 b = buckets[key % m]6 for pair in b:7 if pair[0] == key:8 pair[1] = 9 return10 b.append([key, value])11 12put(5, "a")13put(9, "b")14put(5, "c")15print(buckets[1])
put(5, "c") finds key 5 in the bucket, changes only that pair's value to "c" and returns: the bucket still has two pairs. A dict's d[k] = v works the same way.Why doesn't chaining need a tombstone when deleting a key, the way open addressing does?
get and delete
✓put is done. Finish get (return the value if found, otherwise default) and delete (if found, take it out of the bucket, decrease n and return True; otherwise return False).
3 4 0 True False 2 None
1class HashTable:2 def __init__(self, m=8):3 self.buckets = [[] for _ in range(m)]4 self.n = 05 6 def _bucket(self, key):7 return self.buckets[hash(key) % len(self.buckets)]8 9 def put(self, key, value):10 b = self._bucket(key)11 for pair in b:12 if pair[0] == key:13 pair[1] = value14 return15 b.append([key, value])16 self.n += 117 18 def get(self, key, default=None):19 # search the key's bucket20 return default21 22 def delete(self, key):23 # if found, take it out of the bucket24 return False25 26 def __len__(self):27 return self.n28 29t = HashTable()30for word, count in [("apple", 3), ("pear", 5), ("fig", 2), ("apple", 4)]:31 t.put(word, count)32print(len(t), t.get("apple"), t.get("kiwi", 0))33print(t.delete("pear"), t.delete("pear"), len(t), t.get("pear"))
Load factor and doubling
With chaining, the load factor α = n / m is how many keys a bucket holds on average, and it may exceed 1. A lookup takes about 1 + α/2 comparisons (hit) or α (miss); as long as α is a constant, that is O(1). As keys pile up, α rises with them, so once α passes 1 (Java uses 0.75) the buckets double: every key has to work out its bucket again for the new m, because k % 4 and k % 8 differ.
Add resizing to the class, start with 8 buckets, put in 1000 keys and count all the moves:
1class HashTable:2 def __init__(self, m=8):3 self.buckets = [[] for _ in range(m)]4 self.n = 05 self.moves = 06 7 def _bucket(self, key):8 return self.buckets[hash(key) % len(self.buckets)]9 10 def put(self, key, value):11 b = self._bucket(key)12 for pair in b:13 if pair[0] == key:14 pair[1] = value15 return16 b.append([key, value])17 self.n += 118 if self.n > len(self.buckets): # α > 1: double19 self._resize()20 21 def _resize(self):22 old = self.buckets23 self.buckets = [[] for _ in range(len(old) * 2)]24 for b in old:25 for pair in b:26 self._bucket(pair[0]).append(pair) # work out the bucket again for the new size27 self.moves += 128 print(f"n = {self.n:4}: {len(old)} buckets → {len(self.buckets)}")29 30t = HashTable()31for k in range(1, 1001):32 t.put(k, k * k)33print("stored", t.n, "keys, moved", t.moves, "times in all")34print("longest bucket:", max(len(b) for b in t.buckets))
n = 9: 8 buckets → 16 n = 17: 16 buckets → 32 n = 33: 32 buckets → 64 n = 65: 64 buckets → 128 n = 129: 128 buckets → 256 n = 257: 256 buckets → 512 n = 513: 512 buckets → 1024 stored 1000 keys, moved 1023 times in all longest bucket: 1
That is 9 + 17 + 33 + … + 513 = 1023 moves (each resize happens when n is one more than the buckets) for n = 1000: each key moved only a little more than once on average. Doubling makes resizing amortised O(1), just like list's append. Adding only 8 buckets each time would move everything every 8 keys, O(n²) in all.
The bucket count doubles from 4 to 8, with buckets chosen by k % m. Key 14 moves from which bucket to which?
If each resize only added 8 more buckets (instead of doubling), roughly how many moves would putting n keys take in total?
Double and rehash
✓Finish _resize: build a row of twice as many empty buckets and put every pair from the old buckets back in using the new size, adding 1 to moves for each pair. Starting from 2 buckets, put in 0 to 9; it resizes whenever n exceeds the number of buckets.
16 17 1 [[3, 9]] 49
1class HashTable:2 def __init__(self, m=2):3 self.buckets = [[] for _ in range(m)]4 self.n = 05 self.moves = 06 7 def _bucket(self, key):8 return self.buckets[hash(key) % len(self.buckets)]9 10 def put(self, key, value):11 b = self._bucket(key)12 for pair in b:13 if pair[0] == key:14 pair[1] = value15 return16 b.append([key, value])17 self.n += 118 if self.n > len(self.buckets):19 self._resize()20 21 def _resize(self):22 # a new row of buckets, twice as many; put every old pair back23 pass24 25 def get(self, key):26 for k, v in self._bucket(key):27 if k == key:28 return v29 return None30 31t = HashTable()32for k in range(10):33 t.put(k, k * k)34print(len(t.buckets), t.moves, max(len(b) for b in t.buckets))35print(t.buckets[3], t.get(7))
Compared with open addressing
Both ways depend on a hash that spreads evenly. With a bad one, every key crowds into one bucket and chaining turns into a plain list: each new key is compared with everything in the bucket. Count it for 400 keys:
1class CountingTable:2 def __init__(self, m, hash_fn):3 self.buckets = [[] for _ in range(m)]4 self.hash_fn = hash_fn5 self.compares = 06 7 def add(self, key):8 b = self.buckets[self.hash_fn(key) % len(self.buckets)]9 for k in b:10 self.compares += 111 if k == key:12 return13 b.append(key)14 15keys = list(range(0, 4000, 10)) # 400 keys: 0 10 20 … 399016good = CountingTable(401, lambda k: k)17bad = CountingTable(401, lambda k: 0) # a bad hash: everything works out to 018for k in keys:19 good.add(k)20 bad.add(k)21print("good hash:", good.compares, "comparisons")22print("bad hash:", bad.compares, "comparisons")23print(max(len(b) for b in bad.buckets))
good hash: 0 comparisons bad hash: 79800 comparisons 400
The bad hash made 0 + 1 + … + 399 = 79800 comparisons, O(n²). Open addressing suffers just as much: every key walks past all the slots before it.
| Separate chaining | Open addressing | |
|---|---|---|
| On a collision | goes into the same bucket | tries another slot |
| Load factor | may exceed 1 (0.75–1 is common) | must stay under 1 (2/3 in CPython) |
| Deleting | take it out of the bucket | leave a tombstone |
| Memory | an extra layer per bucket and per item (a node or a small list) | just one row of slots, more compact |
| Memory reads | jump along the chain to elsewhere | neighbouring slots, friendly to the CPU cache |
| Who uses it | Java HashMap, C++ unordered_map | CPython dict / set, Rust HashMap |
In interviews: "How does HashMap handle collisions?": separate chaining; since Java 8, once a bucket holds more than 8 (and the table is big enough) the chain becomes a red-black tree, cutting the worst case from O(n) to O(log n). "Why double when resizing?": each key is moved O(1) times on average; Java's sizes are powers of two, so after doubling a key either stays in its bucket or moves to "old bucket + old size".
Which statement about chaining and open addressing is true?
How you write it at work
In Python you don't write hash tables yourself: dict is one. But the shape "one key, a list of things" is used every day, and defaultdict(list) is a chaining table whose bucket numbers you choose:
1from collections import defaultdict2 3nums = [23, 41, 7, 30, 13, 51, 1, 67]4by_last = defaultdict(list)5for x in nums:6 by_last[x % 10].append(x) # bucket by the last digit7for d in sorted(by_last):8 print(d, by_last[d])
0 [30] 1 [41, 51, 1] 3 [23, 13] 7 [7, 67]
- One key, many values:
defaultdict(list), which puts an empty list in the first time a key is used. - When you do write one (interviews, other languages, teaching), remember four things: build the buckets with a comprehension, have
putcheck for the key first, storenyourself, and double and rehash once α crosses the line. hash(key) % mis fine for the bucket number, but don't print bucket numbers orhash()as results: string values change on every run.
defaultdict(list) groups the words by their first letter. What does it print?
1from collections import defaultdict2 3groups = defaultdict(list)4for w in ["ant", "bee", "ape", "cat", "bat"]:5 groups[w[0]].append(w)6print(dict(groups))
a is used, an empty list appears automatically, then the word is appended. Inside a bucket the order is the order they went in, and the dict keeps the order its keys first appeared in: a, b, c.Summary
Separate chaining: a bucket per slot
- A bucket is a list holding every key that lands on the slot; finding = work out the bucket + compare along it
- put checks for the key first and only changes the value if it is there; deleting takes it out of the bucket, no tombstone
- α = n / m is the average bucket size and may exceed 1; past the line, double and rehash every key for the new size
- Doubling makes resizing amortised O(1); a bad hash that puts everything in one bucket makes it O(n)
1self.buckets = [[] for _ in range(m)]2b = self.buckets[hash(key) % len(self.buckets)]3b.append([key, value])4if self.n > len(self.buckets): self._resize()