NOIDATUT FREE E LEARNING PLATFORM • AKTU B.TECH

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 (indices 0 to m - 1) where records/keys are stored or linked.
  • Load Factor (α): Measures how full the hash table is: α = n / m, where n is the number of stored keys and m is 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:

  1. Step 1 — Insert 22: Compute h(22) = 22 % 7 = 1. Index 1 is empty, so store 22 at slot 1.
  2. Step 2 — Insert 15: Compute h(15) = 15 % 7 = 1. Slot 1 is already occupied by 22! This event is a Collision, so a collision resolution technique is applied.
  3. Step 3 — Insert 31: Compute h(31) = 31 % 7 = 3. Slot 3 is empty, so store 31 at slot 3.

Graphical Representation: Stepwise Hashing & Collision

Stepwise Hashing Trace: h(key) = key % 7, Table Size m = 7 Step 1: Insert 22 h(22) = 22 % 7 = 1 (Free) 0: [ ] 1: [22] 2: [ ] 3: [ ] ← Placed directly Step 2: Insert 15 (Collision!) h(15) = 15 % 7 = 1 (Occupied) 0: [ ] 1: [22] 2: [15] 3: [ ] ← Clash at idx 1 ← Next slot idx 2 Step 3: Insert 31 h(31) = 31 % 7 = 3 (Free) 0: [ ] 1: [22] 2: [15] 3: [31] ← Placed at idx 3

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 at table[idx].
  • Example: With m = 7 and h(k) = k % 7, inserting 22 (22 % 7 = 1) and 15 (15 % 7 = 1) places both in the chain at index 1: 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).

  1. Linear Probing: Checks slots sequentially with step size 1: h'(k, i) = (h(k) + i) % m for i = 0, 1, 2, ...
    Example: If h(15) = 1 is occupied, try i = 1 → (1 + 1) % 7 = 2.
    Drawback: Causes primary clustering (long contiguous blocks of occupied slots that slow down future searches).
  2. Quadratic Probing: Uses a quadratic offset to reduce primary clustering: h'(k, i) = (h(k) + c1·i + c2·i2) % m (commonly (h(k) + i2) % m for i = 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.
  3. 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)) % m for i = 0, 1, 2, ... (where h2(k) ≠ 0 and is chosen coprime to m, e.g., h2(k) = 5 - (k % 5)).
    Advantage: Minimizes both primary and secondary clustering and distributes probes evenly.

Graphical Representation: Collision Resolution Comparison

Collision Resolution Overview (Keys 22 and 15 both hash to index 1) 1. Separate Chaining (Linked List at Slot) idx 0 idx 1 idx 2 22 15 → NULL 2. Open Addressing (Probing Inside Array) 0: [ ] 1: [22] 2: [15] i=0: idx 1 occupied i=1: probes idx 2 → stores 15

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
Advertisement
Advertisement