Sub topic 19
Collision Resolution by Chaining
This chapter assumes you know what a hash function and a collision are (from the previous chapters on hashing). It also assumes you can work with modular arithmetic, singly linked lists, and O-notation.
The idea
A hash table with m slots maps a key k to a slot h(k). Two different keys can map to the same slot, which is a collision. Chaining resolves collisions by letting each slot hold a collection of keys, usually a linked list, instead of a single key.
- Slot j stores the head of a list containing every key with h(k) = j.
- The table never "fills up". It can hold more than m keys, so the load factor α = n/m can exceed 1.
- Every operation first computes h(k), then works only on that one list.
Operations
| Operation | What it does | Cost (given h(k) is O(1)) |
|---|---|---|
| Insert | Compute h(k), put the key at the head of the list | O(1) if you skip the duplicate check; otherwise O(chain length) |
| Search | Compute h(k), scan the list | O(chain length) |
| Delete | Compute h(k), find the node, unlink it | O(chain length) to find it; O(1) to unlink if you already hold the node in a doubly linked list |
Insertion at the head is the usual convention in GATE questions. Read the question for "insert at the end" or "keep each list sorted", because that changes the order inside a chain.
A runnable implementation
Python lists stand in for the linked lists. insert(0, key) models head insertion. In real Python it costs O(chain length), but the duplicate check already scans the chain.
class ChainedHashTable:
def __init__(self, m=7):
self.m = m
self.slots = [[] for _ in range(m)]
self.n = 0
def _h(self, key):
return key % self.m
def search(self, key):
return key in self.slots[self._h(key)]
def insert(self, key):
chain = self.slots[self._h(key)]
if key in chain:
return False
chain.insert(0, key) # head insertion
self.n += 1
return True
def delete(self, key):
chain = self.slots[self._h(key)]
if key in chain:
chain.remove(key)
self.n -= 1
return True
return False
def load_factor(self):
return self.n / self.m
t = ChainedHashTable(7)
for k in [50, 700, 76, 85, 92, 73, 101]:
t.insert(k)
for j, chain in enumerate(t.slots):
print(j, chain)
print("alpha =", t.load_factor())The program prints:
0 [700]
1 [92, 85, 50]
2 []
3 [101, 73]
4 []
5 []
6 [76]
alpha = 1.0To check slot 1 by hand: 50 mod 7 = 1, 85 mod 7 = 1 and 92 mod 7 = 1. Each new key goes to the head, so the chain reads 92, 85, 50.
Expected cost
The standard analysis assumes simple uniform hashing. Each key is equally likely to land in any of the m slots, independently of the others. Then the expected chain length is α = n/m.
- Unsuccessful search: you scan a whole chain. Expected cost is Θ(1 + α).
- Successful search: you scan about half of a chain on average. Expected comparisons are about 1 + α/2 − α/(2n), which is Θ(1 + α).
- If n = O(m), then α = O(1) and all three operations run in O(1) expected time.
- The worst case is Θ(n). If every key hashes to one slot, the table degrades to a single linked list.
The "1" in 1 + α pays for computing h(k) and reaching the slot. The α pays for walking the list.
In the example table the average over all slots for an unsuccessful search is (1+3+0+2+0+0+1)/7 = 1 node examined, which equals α. For a successful search, the keys cost 1 (700), 1 (92), 2 (85), 3 (50), 1 (101), 2 (73) and 1 (76) comparisons. The total is 11, so the average is 11/7 ≈ 1.57. This is a single concrete table, so it need not match the expected-value formula exactly.
Design choices and trade-offs
- Unsorted vs sorted chains. Keeping chains sorted lets an unsuccessful search stop early. It costs more on insert, and the asymptotic cost stays Θ(1 + α).
- Singly vs doubly linked. Doubly linked lists give O(1) delete when you already hold a pointer to the node.
- Resizing. To keep α bounded, real tables double m when α passes a threshold and rehash every key. A single resize costs O(n), but doubling makes the amortized cost per insert O(1).
- Memory. Chaining spends extra memory on pointers and has poor cache locality compared with open addressing. In exchange, it degrades gracefully when α > 1 and deletion is simple.
Common errors
- Capping α at 1. Under chaining, α = 5 is legal and means chains average 5 keys.
- Writing the chain in the wrong order. Head insertion reverses arrival order within a slot. Check the question for head, tail or sorted insertion.
- Forgetting the "1 +". The expected unsuccessful cost is 1 + α, not α alone, when the question counts the slot access.
- Quoting O(1) as the worst case. O(1) is the expected time under uniform hashing. The worst case is Θ(n).
- Using a bad modulus. With h(k) = k mod m, a value of m that shares factors with the key pattern (for example m = 10 with keys ending in 0) piles keys into few slots. This is why a prime m is preferred, as discussed in the hash function chapter.
Exercise
A table has m = 9 slots and uses h(k) = k mod 9 with chaining and head insertion. The keys 5, 28, 19, 15, 20, 33, 12, 17, 10 are inserted in that order. Which slot has the longest chain, and what does that chain contain from head to tail?
Show answer
Slots are 5→5, 28→1, 19→1, 15→6, 20→2, 33→6, 12→3, 17→8, 10→1. Slot 1 holds three keys (28, 19, 10). With head insertion the chain reads 10, 19, 28. Slot 6 has two keys (33, 15). Every other used slot has one key.
Exercise
A chained table stores n = 2000 keys in m = 500 slots under simple uniform hashing. What is α, and how many list nodes does an unsuccessful search examine on average?
Show answer
α = 2000/500 = 4. An unsuccessful search scans a whole chain, so it examines about α = 4 nodes. This is Θ(1 + α) work including the slot access.
Exercise
Why is the worst-case search time of a chained hash table Θ(n), and why does a good hash function make that case unlikely?
Show answer
If all n keys hash to the same slot, the table holds one list of length n, and a search scans up to n nodes. A good hash function spreads keys roughly evenly, so chain lengths stay near α and the expected time is Θ(1 + α).