Data Structures · Visualization
Cuckoo Hashing: Introduction
Cuckoo Hashing
Cuckoo hashing gives every key exactly two possible homes (two tables, two hash functions) — like a cuckoo chick with two nests. Time: O(1) worst-case lookup; O(1) amortised insert. Space: O(n) across two half-empty tables.
Big-O: Worst-case O(1) lookup in ≤ 2 probes.
Cuckoo Hashing: Introduction
Cuckoo HashingCuckoo hashing gives every key exactly two possible homes (two tables, two hash functions) — like a cuckoo chick with two nests. Lookups check at most two slots, so they are worst-case O(1), not just average. Insertions may evict the current resident, which then flies to its own alternate nest, sometimes triggering a whole chain of moves.
How Cuckoo Hashing: Introduction Works
- Hash the key with h1 → try table 1 first.
- If occupied, evict the resident and take its slot.
- The evicted key flies to its alternate table via its other hash.
- Repeat until someone lands in an empty slot — or a cycle forces a rebuild.
Cuckoo Hashing: Introduction Worked Example
Input: Tables size 5; insert 'cat', 'dog'
- 'cat': h1 → slot 2 of table 1, empty → nests there.
- 'dog': h1 → slot 2, occupied by 'cat' → evict 'cat'.
- 'cat' flies to table 2 via h2 → slot 4, empty → settles.
- 'dog' takes slot 2. Both found in ≤ 2 probes.
Output: Table1[2]='dog', Table2[4]='cat' — lookup is 2 probes max
Press ▶ Run to watch it step by step.
def insert(t1, t2, key, kicks=500):
cur, table = key, 1
for _ in range(kicks):
s = h1(cur) if table == 1 else h2(cur)
T = t1 if table == 1 else t2
if T[s] is None: T[s] = cur; return # nested
T[s], cur = cur, T[s] # evict + relocate
table = 3 - table
rebuild_bigger() # cycle: grow + rehash
# example: introCuckoo Hashing: Introduction Time & Space Complexity
When to Use Cuckoo Hashing: Introduction
- Hardware caches and routers where worst-case latency matters
- Real-time systems that cannot tolerate chaining pile-ups
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.