Concept of Hashing and Collision resolution Techniques used in Hashing
Hashing maps keys via a hash function to array indices for ~O(1) search. Collisions (same index for different keys) are handled by chaining (linked lists/buckets) or open addressing (linear/quadratic probing, double hashing) to probe another slot.
Theory & Explanation
Concept of Hashing & Collision Resolution Techniques
1. Concept of Hashing
Hashing is a technique used to map data of arbitrary size (called a search key) to a fixed-size index (called a hash address or bucket index) in a hash table using a mathematical formula called a hash function h(key). Instead of comparing elements sequentially or halving a sorted list, hashing computes the target address directly, achieving an average time complexity of O(1) for search, insertion, and deletion.
- Key: The identifier or search value (for example, a student roll number or product ID).
- Hash Function
h(key): Computes the slot index from the key. A common basic function is the Division / Modulo Method:h(key) = key % TABLE_SIZE. - Hash Table: An array of slots/buckets of size
m(indices0tom - 1) where records/keys are stored or linked. - Load Factor (
α): Measures how full the hash table is:α = n / m, wherenis the number of stored keys andmis the table size. A lower load factor generally means fewer collisions.
2. Step-by-Step Working of Hashing (With Graphical Representation)
Suppose we have a hash table of size m = 7 (indices 0 to 6), hash function h(k) = k % 7, and we insert keys 22, 15, and 31:
- Step 1 — Insert
22: Computeh(22) = 22 % 7 = 1. Index1is empty, so store22at slot1. - Step 2 — Insert
15: Computeh(15) = 15 % 7 = 1. Slot1is already occupied by22! This event is a Collision, so a collision resolution technique is applied. - Step 3 — Insert
31: Computeh(31) = 31 % 7 = 3. Slot3is empty, so store31at slot3.
Graphical Representation: Stepwise Hashing & Collision
3. What Is a Collision & Why Does It Happen?
A collision occurs when two or more distinct keys hash to the same index in the hash table (i.e., key1 ≠ key2, yet h(key1) == h(key2)). Because the number of possible keys is usually larger than the table size (by the Pigeonhole Principle) and table size is finite, collisions are unavoidable and must be handled systematically.
4. Collision Resolution Techniques
Collision resolution methods fall into two main categories: Separate Chaining and Open Addressing.
A. Separate Chaining (Open Hashing)
Each slot in the hash table points to a data structure—usually a singly linked list—that stores all keys hashing to that index.
- How It Works: Compute
idx = h(key)and insert/search/delete the key inside the linked list attable[idx]. - Example: With
m = 7andh(k) = k % 7, inserting22(22 % 7 = 1) and15(15 % 7 = 1) places both in the chain at index1:1 → [22] → [15] → NULL. - Pros & Cons: Never overflows (until memory runs out) and handles high load factors smoothly; requires extra pointer memory and non-contiguous nodes.
B. Open Addressing (Closed Hashing)
All elements are stored directly inside the hash table array itself (no linked lists). When slot h(key) is occupied, a probing sequence checks alternative slots until an empty slot is found (for insertion) or the key/empty slot is found (for search).
-
Linear Probing: Checks slots sequentially with step size 1:
h'(k, i) = (h(k) + i) % mfori = 0, 1, 2, ...
Example: Ifh(15) = 1is occupied, tryi = 1 → (1 + 1) % 7 = 2.
Drawback: Causes primary clustering (long contiguous blocks of occupied slots that slow down future searches). -
Quadratic Probing: Uses a quadratic offset to reduce primary clustering:
h'(k, i) = (h(k) + c1·i + c2·i2) % m(commonly(h(k) + i2) % mfori = 0, 1, 2, ...).
Drawback: Can suffer from secondary clustering (keys with the same initial hash follow the same probe path) and may not probe all slots if table size/constants are chosen poorly. -
Double Hashing: Uses a second hash function
h2(k)as the step size so probe intervals depend on the key itself:h'(k, i) = (h1(k) + i · h2(k)) % mfori = 0, 1, 2, ...(whereh2(k) ≠ 0and is chosen coprime tom, e.g.,h2(k) = 5 - (k % 5)).
Advantage: Minimizes both primary and secondary clustering and distributes probes evenly.
Graphical Representation: Collision Resolution Comparison
5. Summary Comparison Table (For Exams)
| Technique | Formula / Mechanism | Clustering Issue | Key Advantage / Limitation |
|---|---|---|---|
| Separate Chaining | Linked list at index h(k) |
None (uses separate chains) | Handles overflows easily; extra pointer memory |
| Linear Probing | (h(k) + i) % m |
Primary clustering | Simple & cache-friendly; clusters degrade search |
| Quadratic Probing | (h(k) + c1i + c2i2) % m |
Secondary clustering | Reduces primary clusters; may miss slots if full/improper |
| Double Hashing | (h1(k) + i·h2(k)) % m |
Minimal clustering | Uniform spread & fewer probes; two hash functions needed |
6. C Program: Hashing with Separate Chaining & Linear Probing
#include <stdio.h>
#include <stdlib.h>
#define SIZE 7
#define EMPTY -1
// --- 1. Separate Chaining ---
struct Node {
int key;
struct Node next;
};
struct Node chainTable[SIZE] = {NULL};
int hashFunc(int key) {
return key % SIZE;
}
void insertChain(int key) {
int idx = hashFunc(key);
struct Node newNode = (struct Node )malloc(sizeof(struct Node));
newNode->key = key;
newNode->next = chainTable[idx];
chainTable[idx] = newNode;
}
void displayChain() {
printf("Separate Chaining Table:\n");
for (int i = 0; i < SIZE; i++) {
printf("Slot %d: ", i);
struct Node temp = chainTable[i];
while (temp != NULL) {
printf("%d -> ", temp->key);
temp = temp->next;
}
printf("NULL\n");
}
}
// --- 2. Open Addressing (Linear Probing) ---
void insertLinearProbe(int table[], int key) {
int idx = hashFunc(key);
for (int i = 0; i < SIZE; i++) {
int probeIdx = (idx + i) % SIZE;
if (table[probeIdx] == EMPTY) {
table[probeIdx] = key;
return;
}
}
printf("Hash table full! Could not insert %d\n", key);
}
int main() {
int keys[] = {22, 15, 31, 8};
int n = 4;
for (int i = 0; i < n; i++) {
insertChain(keys[i]);
}
displayChain();
int openTable[SIZE];
for (int i = 0; i < SIZE; i++) openTable[i] = EMPTY;
for (int i = 0; i < n; i++) {
insertLinearProbe(openTable, keys[i]);
}
printf("\nLinear Probing Table:\n");
for (int i = 0; i < SIZE; i++) {
printf("Slot %d: %d\n", i, openTable[i]);
}
return 0;
}
Expected Output (C):
Separate Chaining Table:
Slot 0: NULL
Slot 1: 15 -> 22 -> 8 -> NULL
Slot 2: NULL
Slot 3: 31 -> NULL
Slot 4: NULL
Slot 5: NULL
Slot 6: NULL
Linear Probing Table:
Slot 0: -1
Slot 1: 22
Slot 2: 15
Slot 3: 31
Slot 4: 8
Slot 5: -1
Slot 6: -1
7. Python Program: Hashing with Separate Chaining & Linear Probing
SIZE = 7
def hash_func(key: int) -> int:
return key % SIZE
# 1. Separate Chaining
def build_chaining_table(keys):
table = [[] for _ in range(SIZE)]
for k in keys:
table[hash_func(k)].append(k)
return table
# 2. Open Addressing (Linear Probing)
def build_linear_probe_table(keys):
table = [None] SIZE
for k in keys:
base = hash_func(k)
placed = False
for i in range(SIZE):
idx = (base + i) % SIZE
if table[idx] is None:
table[idx] = k
placed = True
break
if not placed:
print(f"Hash table full! Could not insert {k}")
return table
if __name__ == "__main__":
keys = [22, 15, 31, 8]
chain_tbl = build_chaining_table(keys)
print("Separate Chaining Table:")
for idx, bucket in enumerate(chain_tbl):
print(f"Slot {idx}: {bucket}")
probe_tbl = build_linear_probe_table(keys)
print("\nLinear Probing Table:")
for idx, val in enumerate(probe_tbl):
print(f"Slot {idx}: {val}")
Expected Output (Python):
Separate Chaining Table:
Slot 0: []
Slot 1: [22, 15, 8]
Slot 2: []
Slot 3: [31]
Slot 4: []
Slot 5: []
Slot 6: []
Linear Probing Table:
Slot 0: None
Slot 1: 22
Slot 2: 15
Slot 3: 31
Slot 4: 8
Slot 5: None
Slot 6: None