Kodewick
Start learning →
Separate chaining20 / 52

Separate chaining

Lesson 20 of 52 · Part 4 · Hash tables: dict and set · about 18 minutes

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:

k % 11012345678910

Separate chaining, table size 11: colliding keys go one after another in the same bucket, taking no other slot; finding = work out the bucket + compare along it
main.py
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))
Output
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.

Choose one

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?

Guess the outputA wrong guess is fine

Make the buckets with [[]] * m, then put a 7 into bucket 1. What does it print?

1m = 32buckets = [[]] * m3buckets[1].append(7)4print(buckets)

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):

main.py
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))
Output
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.

k % 11022116724613345678413095310

Deleting: take it out of the bucket; the other keys in the same bucket stay where they are and are still found

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().

Guess the outputA wrong guess is fine

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))
Fill inTap one to fill a blank; tap a blank to take it back

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])
Choose one

Why doesn't chaining need a tombstone when deleting a key, the way open addressing does?

Exercise 1

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).

It should print
3 4 0
True False 2 None
exercise1.py
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"))
Output
Press Run or Ctrl+Enter

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.

k % m0159132263

4 buckets holding 5 keys (bucket 1: 5, 9, 13; bucket 2: 2, 6), α > 1: double to 8 buckets and spread every key again by k % 8

Add resizing to the class, start with 8 buckets, put in 1000 keys and count all the moves:

main.py
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))
Output
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.

Choose one

The bucket count doubles from 4 to 8, with buckets chosen by k % m. Key 14 moves from which bucket to which?

Choose one

If each resize only added 8 more buckets (instead of doubling), roughly how many moves would putting n keys take in total?

Exercise 2

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.

It should print
16 17 1
[[3, 9]] 49
exercise2.py
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))
Output
Press Run or Ctrl+Enter

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:

main.py
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))
Output
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 chainingOpen addressing
On a collisiongoes into the same buckettries another slot
Load factormay exceed 1 (0.75–1 is common)must stay under 1 (2/3 in CPython)
Deletingtake it out of the bucketleave a tombstone
Memoryan extra layer per bucket and per item (a node or a small list)just one row of slots, more compact
Memory readsjump along the chain to elsewhereneighbouring slots, friendly to the CPU cache
Who uses itJava HashMap, C++ unordered_mapCPython 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".

Choose one

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:

main.py
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])
Output
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 put check for the key first, store n yourself, and double and rehash once α crosses the line.
  • hash(key) % m is fine for the bucket number, but don't print bucket numbers or hash() as results: string values change on every run.
Guess the outputA wrong guess is fine

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))

Summary

Take-away

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()