DATA STRUCTURES PROGRAM • HEAPS, HASHING & DISJOINT SETS

Implement Hashing with Separate Chaining

Learn how to implement hashing with separate chaining using a clear C program.

IntermediateHash tableChainingCollision handling

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
0: 15 10
2: 17 12 7

COMPLETE C PROGRAM

Complete C implementation

dsa-hash-table-separate-chaining.c
Open in compiler
#include <stdio.h>
#include <stdlib.h>

struct Node { int key; struct Node *next; };
void insert(struct Node *table[], int key)
{
    int bucket = key % 5;
    struct Node *node = malloc(sizeof *node);
    if (node == NULL) exit(EXIT_FAILURE);
    node->key = key; node->next = table[bucket]; table[bucket] = node;
}
void clear(struct Node *table[])
{
    for (int bucket = 0; bucket < 5; bucket++)
        while (table[bucket] != NULL) {
            struct Node *removed = table[bucket];
            table[bucket] = removed->next; free(removed);
        }
}

int main(void)
{
    struct Node *table[5] = {NULL};
    int keys[] = {10, 15, 7, 12, 17};
    for (int index = 0; index < 5; index++) insert(table, keys[index]);
    for (int bucket = 0; bucket < 5; bucket++) {
        printf("%d:", bucket);
        for (struct Node *node = table[bucket]; node != NULL; node = node->next) printf(" %d", node->key);
        putchar('\n');
    }
    clear(table);
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

0: 15 10
2: 17 12 7
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Store colliding keys in a linked list owned by the hashed bucket.
  3. Display the computed result.

Store colliding keys in a linked list owned by the hashed bucket.

EFFICIENCY

Time and space complexity

Time complexity

O(n)

Auxiliary space

O(n)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.