Data Structures · Visualization
Cuckoo Hashing: Insert & Displacement
Cuckoo Hashing
Insertion is a polite eviction chain: the newcomer kicks out whoever sits in its first-choice slot, the victim retries its second choice, and so on. Time: O(1) amortised; rebuild O(n) on cycles. Space: Load must stay under ~50% per table.
Big-O: Worst-case O(1) lookup in ≤ 2 probes.
Cuckoo Hashing: Insert & Displacement
Cuckoo HashingInsertion is a polite eviction chain: the newcomer kicks out whoever sits in its first-choice slot, the victim retries its second choice, and so on. Most chains end in a few hops. If the same keys keep cycling (a loop), the tables are too full — rehash everything bigger with fresh hash functions.
How Insert & Displacement Works
- Try slot h1 in table 1; if free, done.
- Otherwise evict the resident and occupy it.
- Send the victim to its other table/slot.
- Cap the kicks (e.g. 500); on loop, grow + rehash all.
Insert & Displacement Worked Example
Input: Insert 'emu' into Table1[2]='dog', Table2[4]='cat'
- 'emu' h1 → slot 2, occupied → evict 'dog'.
- 'dog' h2 → slot 1 of table 2, empty → settles.
- 'emu' nests at Table1[2]. Chain length 1.
- Had slot 1 been full, 'dog' would have bounced back — watch for cycles.
Output: Table1[2]='emu', Table2[1]='dog' — 1 displacement
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: insertBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Insert & Displacement Time & Space Complexity
When to Use Insert & Displacement
- In-memory key-value stores with strict tail latency
- Compiler symbol tables with predictable lookup budgets
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.