C Collision Handling

Intermediate
6 min read
Updated: Nov 2026
1 example

When Two Keys Share a Slot

A collision occurs when two keys hash to the same slot. By the birthday paradox they appear surprisingly early, so every table needs a strategy. Separate chaining stores colliding keys in a list per slot. Open addressing stores them in other slots of the same array (linear probing, quadratic probing, double hashing).

Remember
/* chaining : slot -> list of keys
   probing  : try slot, slot+1, slot+2, ... */

Cheat Sheet

Keep these facts handy while you work with Collision Handling in C.

TopicDetail
ChainingList per slot
Linear probingNext free slot
Double hashingSecond hash gives the step
MetricLoad factor n / m

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Separate Chaining.

Example 1 — Count keys per slot

Six keys, five slots.

C
#include <stdio.h>

int main(void) {
    int keys[] = {10, 15, 22, 27, 33, 40};
    int per[5] = {0};
    int collisions = 0;

    for (int i = 0; i < 6; i++) per[keys[i] % 5]++;

    for (int s = 0; s < 5; s++) {
        printf("slot %d: %d key(s)\n", s, per[s]);
        if (per[s] > 1) collisions += per[s] - 1;
    }
    printf("collisions: %d\n", collisions);
    return 0;
}

How It Works

  1. 10, 15, and 40 all map to slot 0.
  2. 22 and 27 share slot 2.
  3. Collisions are the keys beyond the first in each slot: 2 + 1 = 3.

Edge Cases & Pitfalls

Check these before relying on Collision Handling in real programs.

overwrite

Overwriting on collision

Storing straight into the slot silently loses the earlier key.

cluster

Primary clustering

Linear probing creates runs of occupied slots that slow later inserts.

Key Takeaways

  • Collisions are normal.
  • Chaining or probing.
  • Load factor drives cost.

One line: A collision occurs when two keys hash to the same slot.

Frequently Asked Questions

Two different keys producing the same table index.
Not in general, because there are more possible keys than slots. Only perfect hashing for a fixed key set can avoid them.
Continue with "C Separate Chaining" next. Resolve collisions with a linked list per slot and print the buckets. The C Hash Tables hub lists every topic in order.

Next: Separate Chaining

Resolve collisions with a linked list per slot and print the buckets.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful