Data Structures Β· Visualization
Hash Table: Collision Handling (Chaining)
Hash Table
Separate chaining resolves hash collisions by storing a small linked list (or bucket) of entries at each array slot β when two keys hash to the same index, they simply live side by side in that slot's list. Time: Average O(1), worst case O(n) if all keys collide. Space: O(n).
Big-O: Average O(1) per operation; worst case O(n) on collisions.
Hash Table: Collision Handling (Chaining)
Hash TableSeparate chaining resolves hash collisions by storing a small linked list (or bucket) of entries at each array slot β when two keys hash to the same index, they simply live side by side in that slot's list.
How Collision Handling (Chaining) Works
- Compute the key's hash and reduce it modulo the table size to get a bucket index.
- If the bucket is empty, create a new list and insert the entry.
- If the bucket already has entries, append (or prepend) the new entry to that bucket's list.
- To look up a key, hash to the bucket, then linearly scan that bucket's list comparing keys.
- Resize (rehash all entries into a bigger table) when the average chain length grows too long.
Collision Handling (Chaining) Worked Example
Input: Insert keys 'cat' and 'act' which both hash to bucket 3 in a table of size 8
- hash('cat') % 8 = 3 β bucket 3 is empty β bucket3 = ['cat']
- hash('act') % 8 = 3 β collision β bucket3 = ['cat', 'act']
- Lookup 'act': go to bucket 3, scan list, compare 'cat' (no), 'act' (match)
Output: Both keys coexist in bucket 3's chain; lookup costs 2 comparisons worst case
Press βΆ Run to watch it step by step.
# Hash map: key -> value, O(1) average
scores = {}
scores["alice"] = 90 # insert
v = scores.get("bob", 0) # get with default
del scores["alice"] # delete
if "bob" in scores: # membership
print("present")
# example: insert key=catBehind 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.
Collision Handling (Chaining) Time & Space Complexity
When to Use Collision Handling (Chaining)
- General-purpose hash map implementations (Java HashMap buckets)
- Symbol tables in compilers
- Caching layers
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.