Two keys, one slot: collisions and chaining
After this: Explain what a collision is, why it cannot be avoided, and how chaining handles it.
On this page · 6 sections · 3 checks
In the last lesson every key had a slot to itself, because we chose the keys with care. Real keys do not behave so well. Insert cat, then insert act. Where does act land?
Try it before you read on. The codes are a = 97, c = 99 and t = 116.
- The sum is 97 + 99 + 116 = 312.
- 312 % 8 = 0, so
actbelongs in slot 0. - But
catis already in slot 0.
The two words have the same letters, so they have the same sum and the same slot. What should the table do? It must not replace cat, or cat would be lost.
Two keys, one slot
When two different keys land in the same slot, it is called a . It is not a bug, and it is not rare.
Think back to the coat room. If nine coats arrive and there are eight hooks, at least two coats must share a hook. A table has the same problem. It has a fixed number of slots, and there are far more possible keys than slots. So some keys must share a slot, however good the hash function is.
A short list in each slot
The answer in this tutorial is to let each slot hold a short list of pairs, not only one pair. When a key lands in a slot that already holds something, its pair is added to the end of that slot's list. This list is called the slot's , and this way of handling collisions is called .
After inserting cat with value 3 and act with value 5, slot 0 looks like this.
| Slot | Chain |
|---|---|
| 0 | (cat, 3), then (act, 5) |
Now look up act. Going along a chain and comparing keys is called walking the chain.
- Hash the key to reach slot 0.
- Compare the first stored key,
cat. It does not match. - Compare the next stored key,
act. It matches, so the answer is 5.
That took two comparisons. Now look up tac, which has the same letters but was never inserted.
- Hash the key to reach slot 0.
- Compare
cat. It does not match. - Compare
act. It does not match. - The chain has ended, so the answer is Nonenull.
So chaining changes both operations a little.
- Insert goes to the slot and walks the chain to see whether the key is already there. If it is, its value is replaced, so that a key is never stored twice. If it is not, the new pair goes at the end of the chain.
- Lookup goes to the slot and walks the chain, comparing keys from the start, until it finds a match or the chain ends.
This is why a slot stores the key next to the value. Without the key, a lookup that reached slot 0 could not tell cat from act.
Watch it happen
Here are five operations, in order. The second one asks you to predict the slot before it runs. You can step through each operation with the controls, or let it play.
- Insert cat → 3This key lands in an empty slot, so the pair goes straight in.
- Insert act → 5
- Insert tac → 7
- Look up tac
- Look up tca
- 0—
- 1—
- 2—
- 3—
- 4—
- 5—
- 6—
- 7—
Start with the first task above, or try any key.
- count
- 0
- load
- 0.00
- compares
- 0
Notice two things. First, the collision lost nothing: all the pairs are still there, in the order they arrived. Second, the two lookups cost the same, because a key that is missing can only be ruled out by walking the whole chain.
The code
SimpleHashMap has three changes from the last lesson: each slot now starts as an empty list, put and get walk the chain, and count keeps the number of pairs.
class SimpleHashMap: def __init__(self, capacity=8): self.capacity = capacity self.buckets = [[] for _ in range(capacity)] # each slot holds a chain self.count = 0
def _index(self, key): return sum(ord(ch) for ch in key) % self.capacity
def put(self, key, value): bucket = self.buckets[self._index(key)] for pair in bucket: if pair[0] == key: # same key again: replace the value pair[1] = value return bucket.append([key, value]) # new key: append to the chain self.count += 1
def get(self, key): bucket = self.buckets[self._index(key)] for stored_key, value in bucket: if stored_key == key: return value return Noneimport java.util.ArrayList;import java.util.List;
public class SimpleHashMap { private static class Pair { String key; int value; Pair(String key, int value) { this.key = key; this.value = value; } }
private final int capacity; private final List<List<Pair>> buckets; // each slot holds a chain private int count = 0;
public SimpleHashMap() { this(8); }
public SimpleHashMap(int capacity) { this.capacity = capacity; this.buckets = new ArrayList<>(); for (int i = 0; i < capacity; i++) buckets.add(new ArrayList<>()); }
private int index(String key) { int sum = 0; for (char ch : key.toCharArray()) sum += ch; // a char is its code return sum % capacity; }
public void put(String key, int value) { List<Pair> bucket = buckets.get(index(key)); for (Pair pair : bucket) { if (pair.key.equals(key)) { // same key again: replace the value pair.value = value; return; } } bucket.add(new Pair(key, value)); // new key: append to the chain count++; }
public Integer get(String key) { // Integer, not int, so it can be null List<Pair> bucket = buckets.get(index(key)); for (Pair pair : bucket) { if (pair.key.equals(key)) { return pair.value; } } return null; }}Here is how to read it.
bucketsnow holds one list per slot. Each list is a chain, and each starts empty.countis the number of pairs stored in the table.putwalks the chain first. If it finds the key, it replaces the value and stops. If the loop ends, the key is new, so it adds the pair at the end of the chain and adds one tocount.- The highlighted lines are the chain walk in
get. They look at each stored key in turn, and return the value of the first key that matches. If the chain runs out, they return Nonenull.
m = SimpleHashMap()m.put("cat", 3)m.put("act", 5) # same slot as "cat": appended to the chainprint(m.get("act")) # walks slot 0: compares "cat", then "act"print(m.get("tac")) # also slot 0, but not in the chain5 None
SimpleHashMap m = new SimpleHashMap();m.put("cat", 3);m.put("act", 5); // same slot as "cat": appended to the chainSystem.out.println(m.get("act")); // walks slot 0: compares "cat", then "act"System.out.println(m.get("tac")); // also slot 0, but not in the chain5 null
Both lookups go to slot 0. The first compares cat, then act, and returns 5. The second compares both stored keys, finds that neither is tac, and returns Nonenull.
Check yourself
Attempts are unlimited, hints are there if you want them, and every option explains itself.
Why must each slot store the key as well as the value?
After inserting cat, act and tac in that order, how many key comparisons does get(tac) make?
Starting from an empty table, run put(cat, 3), put(act, 5), put(tac, 7), then put(act, 9). What does slot 0's chain look like afterwards?
Connect
Chains are usually short, and that keeps lookups fast. Now picture the opposite: a hash function that gives the same slot for every key. Every pair would land in one chain, and a lookup would have to go along it comparing keys one by one, as if the hash map were a plain list. The lesson How fast is a hash map, really? measures what that costs.
- Explain what a collision is and why no hash function can avoid them.
- Describe chaining: each slot holds a list, insert adds to the end, and lookup walks the list and compares keys.
- Say why the key is stored with the value.
- Count the comparisons a lookup makes, whether or not it finds the key.