0
0
DSA Pythonprogramming

Collision Handling Using Chaining in DSA Python

Choose your learning style9 modes available
Mental Model
When two keys want to go to the same spot in a table, we keep them in a small linked list at that spot.
Analogy: Imagine a mailbox with several slots. If two letters come for the same slot, we put them in a small pile inside that slot instead of losing one.
Hash Table:
Index 0 -> null
Index 1 -> 21 -> 41 -> null
Index 2 -> 32 -> null
Index 3 -> null
Index 4 -> 14 -> null
Dry Run Walkthrough
Input: Insert keys 14, 21, 32, 41 into a hash table of size 5 using chaining
Goal: Show how collisions are handled by adding nodes to linked lists at the same index
Step 1: Insert 14, hash index = 14 % 5 = 4
Index 4 -> 14 -> null
Why: 14 goes to index 4, no collision yet
Step 2: Insert 21, hash index = 21 % 5 = 1
Index 1 -> 21 -> null
Index 4 -> 14 -> null
Why: 21 goes to index 1, no collision yet
Step 3: Insert 32, hash index = 32 % 5 = 2
Index 1 -> 21 -> null
Index 2 -> 32 -> null
Index 4 -> 14 -> null
Why: 32 goes to index 2, no collision yet
Step 4: Insert 41, hash index = 41 % 5 = 1, collision with 21
Index 1 -> 21 -> 41 -> null
Index 2 -> 32 -> null
Index 4 -> 14 -> null
Why: 41 collides at index 1, so we add it to the linked list there
Result:
Index 0 -> null
Index 1 -> 21 -> 41 -> null
Index 2 -> 32 -> null
Index 3 -> null
Index 4 -> 14 -> null
Annotated Code
DSA Python
class Node:
    def __init__(self, key):
        self.key = key
        self.next = None

class HashTable:
    def __init__(self, size):
        self.size = size
        self.table = [None] * size

    def hash_function(self, key):
        return key % self.size

    def insert(self, key):
        index = self.hash_function(key)  # find index
        new_node = Node(key)  # create new node
        if self.table[index] is None:
            self.table[index] = new_node  # no collision, place node
        else:
            curr = self.table[index]
            while curr.next is not None:
                curr = curr.next  # move to end of chain
            curr.next = new_node  # add new node at end

    def __str__(self):
        result = []
        for i in range(self.size):
            curr = self.table[i]
            chain = []
            while curr:
                chain.append(str(curr.key))
                curr = curr.next
            chain_str = ' -> '.join(chain) + ' -> null' if chain else 'null'
            result.append(f'Index {i} -> {chain_str}')
        return '\n'.join(result)

# Driver code
ht = HashTable(5)
keys = [14, 21, 32, 41]
for key in keys:
    ht.insert(key)
print(ht)
index = self.hash_function(key) # find index
compute hash index for the key
if self.table[index] is None:
check if slot is empty, no collision
curr = self.table[index] while curr.next is not None: curr = curr.next
traverse linked list to find last node
curr.next = new_node # add new node at end
append new node to handle collision
OutputSuccess
Index 0 -> null Index 1 -> 21 -> 41 -> null Index 2 -> 32 -> null Index 3 -> null Index 4 -> 14 -> null
Complexity Analysis
Time: O(n) in worst case because all keys could hash to the same index forming a long chain
Space: O(n) because we store all keys in linked lists inside the table
vs Alternative: Compared to open addressing which stores all keys in the array itself, chaining uses extra linked lists but handles collisions more flexibly
Edge Cases
Inserting into an empty hash table
Key is placed directly without collision
DSA Python
if self.table[index] is None:
Multiple keys hashing to same index
Keys are chained in linked list at that index
DSA Python
while curr.next is not None:
Hash table size is 1 (all keys collide)
All keys form one long chain at index 0
DSA Python
while curr.next is not None:
When to Use This Pattern
When you see a hash table with collisions and need to store multiple keys at one index, use chaining to keep keys in a linked list at that index.
Common Mistakes
Mistake: Overwriting existing key at index instead of chaining
Fix: Traverse the linked list and add new node at the end instead of replacing
Mistake: Not handling empty slot before chaining
Fix: Check if slot is None and insert directly if so
Summary
It stores multiple keys at the same hash index using linked lists to handle collisions.
Use it when your hash function causes collisions and you want to keep all keys safely.
The key insight is to keep a small chain of keys at each index instead of losing or overwriting them.