5. Hash Tables (Separate Chaining)
Turn a key into a bucket index with a hash function, then store the pair there. Average O(1) insert, lookup and delete; collisions are handled with chains or probing.
How it works
A hash table computes hash(key) % number_of_buckets to decide where a key lives. Two different keys can land in the same bucket (a collision). With separate chaining, each bucket holds a small list of (key, value) pairs and we scan that list.
This example uses a simple deterministic string hash h = h * 31 + ord(ch) so the numbers are reproducible (Python’s built-in hash() for strings changes between runs). Real tables also resize when the load factor (items / buckets) passes a threshold, which keeps chains short.
Diagram
flowchart LR
b0["bucket 0"]
b0 --> e0["empty"]
b1["bucket 1"]
b1 --> k_fish["fish: 4"]
b2["bucket 2"]
b2 --> k_cat["cat: 1"]
k_cat --> k_bird["bird: 3"]
b3["bucket 3"]
b3 --> e3["empty"]
b4["bucket 4"]
b4 --> k_dog["dog: 9"]
k_dog --> k_cow["cow: 5"]
Step-by-step trace
Input: 5 buckets. Put cat, dog, bird, fish, cow; update dog; then get bird and rat.
| Operation | hash(key) | Bucket | Result | Chain in that bucket |
|---|---|---|---|---|
| put(cat, 1) | 98262 | 2 | insert | cat:1 |
| put(dog, 2) | 99644 | 4 | insert | dog:2 |
| put(bird, 3) | 3024057 | 2 | insert | cat:1 -> bird:3 |
| put(fish, 4) | 3143256 | 1 | insert | fish:4 |
| put(cow, 5) | 98699 | 4 | insert | dog:2 -> cow:5 |
| put(dog, 9) | 99644 | 4 | update | dog:9 -> cow:5 |
| get(bird) | 3024057 | 2 | found 3 | cat:1 -> bird:3 |
| get(rat) | 112677 | 2 | KeyError | cat:1 -> bird:3 |
Result: cat and bird collide in bucket 2, dog and cow collide in bucket 4. rat hashes to bucket 2, the chain is scanned and the key is not found.
Complexity
| Operation | Time | Space |
|---|---|---|
| Insert / lookup / delete (average) | O(1) | O(n) total |
| Insert / lookup / delete (worst, all collide) | O(n) | O(n) total |
| Resize (rehash everything) | O(n) | O(n) |
Python reference implementation
def string_hash(key):
"""Deterministic polynomial string hash (Python's hash() is randomized)."""
h = 0
for ch in key:
h = (h * 31 + ord(ch)) % (2 ** 32)
return h
class HashTable:
"""Hash map with separate chaining."""
def __init__(self, num_buckets=5):
self.buckets = [[] for _ in range(num_buckets)]
self.size = 0
def _bucket(self, key):
return self.buckets[string_hash(key) % len(self.buckets)]
def put(self, key, value):
bucket = self._bucket(key)
for pair in bucket:
if pair[0] == key:
pair[1] = value # key exists: update
return "update"
bucket.append([key, value]) # new key: add to the chain
self.size += 1
return "insert"
def get(self, key):
for k, v in self._bucket(key):
if k == key:
return v
raise KeyError(key)
Common mistakes and tips
- Keys must be immutable (or at least not change while stored) or they get lost in the wrong bucket.
- Iteration order of a hash set is not sorted; sort explicitly if order matters.
- Most ‘find a pair / count things / seen before’ problems become O(n) with a dict or set.
The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.
| Previous: Queues (Two-Stack Queue) | Next: LRU Cache (Hash Map + Doubly Linked List) |