Inside a Hash Table
Data Structures & Algorithms · Hash Maps & Sets · Intermediate · 20 min
Open up dict and set: how a hash function picks a slot, what happens on a collision (chaining vs linear probing), and why the table resizes when the load factor gets high.
A wall of numbered pigeonholes. A formula turns every key into a pigeonhole number, so you walk straight to the right hole instead of searching the whole wall.
The idea in everyday words
A hotel gives you a room number computed from your surname, so the receptionist never has to search the register. Sometimes two guests get the same number: either the room gets bunk beds (chaining), or the second guest takes the next free room down the corridor (linear probing). When the hotel gets too full, it moves to a building twice the size and everyone is assigned a new room.
From key to slot: the hash function
A hash table is an array of slots (often called buckets) plus a rule for choosing the slot.
- A hash function turns the key into a big integer:
hash("ana")→ some number. - Modulo squeezes it into the table:
index = hash(key) % capacity. - Go straight to
slots[index]. One jump, like array indexing: O(1).
cap = 8
for key in [12, 7, 20]:
print(key, "-> slot", hash(key) % cap) # small ints hash to themselves
print(hash("ana") % cap) # strings: varies between runs
A good hash function is:
- Deterministic: the same key always gives the same number (within one run).
- Well spread: similar keys land in different slots.
- Fast to compute.
Keys must be hashable: Python must be able to compute a hash for them that never changes while they are stored. If a list could change after being stored, its hash would change and you could never find it again. Built-in immutable values (int, str, and tuples that only hold hashable things) are hashable; lists, dicts and sets are not. That is why dict accepts (1, 2) but rejects [1, 2], and also rejects (1, [2]), a tuple holding a list. (Objects of your own classes are hashable by default too: they hash by identity, unless the class defines __eq__ without __hash__.)
(Python randomises string hashes each time the program starts, for security. Never rely on a specific string hash value.)
Collisions are guaranteed
There are endless possible keys but only capacity slots, so two keys will eventually land in the same slot. That is a collision.
With capacity 5: 12 % 5 = 2, 7 % 5 = 2, 22 % 5 = 2. Three keys, one slot.
Collisions do not break correctness, they only cost time. Every hash table needs a collision strategy. The two classic ones are separate chaining and open addressing.
The surprising maths (the birthday paradox): with 23 people, there is a better than 50% chance two share a birthday out of 365 days. Collisions show up long before the table is full.
Fix 1: separate chaining
Each slot holds a small list (a chain) of all entries that hashed there.
- Insert: hash to the slot, append to its chain (if the key is not already there).
- Find: hash to the slot, scan only that chain.
- Delete: remove from the chain.
cap = 5
buckets = [[] for _ in range(cap)]
for key in [12, 7, 22, 3]:
buckets[key % cap].append(key)
print(buckets) # slot 2 holds a chain of three
print(22 in buckets[22 % cap])
The cost of a lookup is the length of one chain. If keys spread well, chains stay short (about n / capacity items on average), so operations are O(1) on average. In the worst case (all keys in one slot) a lookup degrades to O(n).
Java's HashMap uses chaining (and turns very long chains into small trees).
Fix 2: open addressing with linear probing
Here every slot holds at most one entry. On a collision, probe (try) the next slot, (i + 1) % capacity, until you find an empty one.
Insert 12, 7, 22 into 5 slots: 12 → slot 2. 7 → 2 is taken, try 3, free. 22 → 2 taken, 3 taken, 4 free.
cap = 5
slots = [None] * cap
for key in [12, 7, 22]:
i = key % cap
while slots[i] is not None:
i = (i + 1) % cap # wrap around at the end
slots[i] = key
print(slots)
- Find: start at the home slot, walk forward until you hit the key (found) or an empty slot (not present).
- Delete cannot just empty a slot, or later searches would stop too early. Mark it with a tombstone ("something was here, keep walking").
- Downside: clustering. Occupied slots clump together, and each new collision makes the clump longer.
Probing is cache-friendly (everything sits in one array). CPython's dict uses open addressing with a smarter, pseudo-random probe sequence.
Load factor, resizing and rehashing
The load factor is how full the table is:
λ = n / capacity (n = number of keys stored)
As λ grows, chains get longer and probe runs get longer. So the table keeps λ below a limit (around 0.75 is common; probing tables often stay lower), and when an insert pushes it over:
- Allocate a new array, usually twice the capacity.
- Rehash every key into it. The slot depends on
capacity(key % cap), so every key may move. - Throw away the old array.
A resize costs O(n), but like a dynamic array it happens rarely enough that inserts stay O(1) amortized.
| Operation | Average | Worst case |
|---|---|---|
| insert / find / delete | O(1) | O(n), when everything collides |
| resize | O(n) | O(n), but rare: amortized O(1) per insert |
Mental model: a hash table trades memory (empty slots) for speed (short chains).
Step by step
- Empty table:
capacity = 5, max load factor 0.75. All slots empty.
- Insert 12:
12 % 5 = 2. Slot 2 is empty: store 12 there. n = 1, λ = 0.2.
- Insert 7:
7 % 5 = 2: collision! Linear probing tries slot 3: empty, store 7. n = 2, λ = 0.4.
- Insert 22:
22 % 5 = 2: taken. Slot 3: taken. Slot 4: free, store 22. Notice the cluster at slots 2-4 growing.
- Insert 3:
3 % 5 = 3: taken. Slot 4: taken. Wrap around to slot 0: free. n = 4, λ = 0.8 > 0.75.
- Resize to 10:
New array of 10 slots. Rehash each key with % 10: 3 → slot 3, 12 → slot 2, 7 → slot 7, 22 → slot 2 is taken so probe to 3, taken, then 4. Now λ = 0.4 and runs are short again.
Code example
class ProbingTable:
def __init__(self, cap=5, max_load=0.75):
self.cap, self.n, self.max_load = cap, 0, max_load
self.slots = [None] * cap
def _find_slot(self, key):
i = key % self.cap
while self.slots[i] is not None and self.slots[i] != key:
i = (i + 1) % self.cap
return i
def put(self, key):
i = self._find_slot(key)
if self.slots[i] is None:
self.slots[i] = key
self.n += 1
if self.n / self.cap > self.max_load:
self._resize(2 * self.cap)
def contains(self, key):
return self.slots[self._find_slot(key)] == key
def _resize(self, new_cap):
old = [k for k in self.slots if k is not None]
self.cap, self.n = new_cap, 0
self.slots = [None] * new_cap
for k in old:
self.put(k)
print(" resized to", new_cap, "->", self.slots)
t = ProbingTable()
for key in [12, 7, 22, 3, 17, 30, 9]:
t.put(key)
print("put", key, "| load", round(t.n / t.cap, 2), "|", t.slots)
print("contains 22?", t.contains(22), "| contains 8?", t.contains(8))Complexity
- Time: O(1) average per insert or lookup while the load factor is bounded; O(n) worst case when keys pile into one cluster or chain. Resizing is O(n) but amortized O(1) per insert.
- Space: O(capacity) = O(n): the table keeps some empty slots on purpose so chains and probe runs stay short.
Interview tips
If asked 'why is a dict lookup O(1)?', walk through: hash → index → one slot → short chain/probe, and add 'on average, with a good hash and a bounded load factor'.
Know both collision strategies and one trade-off each: chaining is simple and tolerates high load; probing is cache-friendly but suffers clustering and needs tombstones for deletes.
Mention resizing and rehashing when discussing performance: occasional O(n) spikes, amortized O(1).
Explain why mutable objects cannot be keys: a changed key would hash to a different slot and be lost.
'Design HashMap' is a real interview question: an array of buckets with chaining is the easiest correct answer.
Challenge: Linear Probing Insert
Simulate a hash table with linear probing. Start with size empty slots (None). Insert each key from keys in order:
- home slot =
key % size - if that slot holds a different key, try the next slot, wrapping around:
(i + 1) % size - if you find the same key, it is a duplicate: do nothing
Keys are non-negative integers and there are never more distinct keys than slots. Return the final table.
Example: probe_insert([12, 22, 5, 15], 10) → [None, None, 12, 22, None, 5, 15, None, None, None]
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- Design HashMap (Easy)
- Design HashSet (Easy)
- Two Sum (Easy)
- Longest Consecutive Sequence (Medium)
More in Hash Maps & Sets
Previous: Hash Maps (Dictionaries) · Next: Trees, DFS & BFS