AlgoTales · Roadmap

Collision handling

Intermediate · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A hash table turns a key such as a username into a slot number so it can jump straight to the data. Sometimes two different keys land in the same slot, which is called a collision. Collision handling is the rule for what to do then, so nothing gets lost or overwritten.

Practical use cases

  • Web app: Two usernames, one slot. A sign-up page keeps a table of taken usernames so it can say "already taken" instantly. When "rahul_k" and "sneha22" both map to slot 41, the code must keep both names there instead of overwriting the first. With a proper collision rule, both users get correct answers and nobody is told the wrong name is free.
  • Web app: Cart items keyed by product id. A shopping cart stores quantities in an in-memory map keyed by product id. Two ids may share a slot internally, and if the map handled that badly, one product would silently vanish from the cart. Good collision handling is why adding 500 different items still shows every single one at checkout.
  • System: Hash flooding attacks. Attackers can send thousands of form fields whose names all collide on purpose, so the server spends its time walking one crowded slot. Modern languages randomise their hashing and handle collisions carefully so a single malicious request cannot freeze a web server.

The story: Two Guests, One Chair

At Zoya's cousin's wedding, the family used a clever seating plan: each guest's name went through a small recipe that gave a table number. No one needed a list to find their seat. It worked beautifully, until the number gave Raju and Bhaskar the same table, and the table had only one chair left.

The wedding planner, Mrs. Kapoor, had seen this before. "This always happens when there are more guests than tables. It is not a failure, it is a collision. We just need a rule for it." She gave the family two choices. Rule A: bring an extra bench to the table so both can sit (chaining). Rule B: if the table is full, walk to the next table, then the next, until you find a free chair (open addressing).

Mira loved the idea of two solutions to one problem. "But how will Bhaskar's friends find him?" Mrs. Kapoor said, "They use the same recipe, go to the same table, and then follow the same rule: look on the bench, or walk table to table." Collision handling is the rule that keeps a hash table correct when two keys want the same bucket.

How to spot this problem, and where you need it

You use a table to find things instantly by key, but sometimes two different keys want the same spot, and you must not lose or mix up either of them.

Signs you need it

  • You are storing records by a computed number (hash, id modulo size) and notice two different records can end up with the same number.
  • A lookup sometimes returns the wrong record, or a saved record disappears after another one is added.
  • The problem says "implement a hash map from scratch" or asks what happens when two keys give the same index.
  • A table that was instant with 100 entries slows down as it fills up because many keys crowd into the same few slots.

Where to use it in a project

  • Building your own cache, session store or lookup table instead of relying on the language built-in map.
  • Choosing between hash-based and tree-based indexes in a database and understanding why a poor hash makes lookups slow.

The solution

Pick one of two rules in advance. Either chaining: each slot holds a small list, and colliding keys simply join that list. Or open addressing: if the slot is taken, walk to the next free slot by a fixed pattern. On lookup, go to the slot and repeat the same rule until you find the key or reach an empty place. Keep the table from getting too full and collisions stay rare.

Payoff: Before: a collision overwrote a user and one record was lost. After: both are stored and found in one or two checks, even in a table of 100,000 keys.

Explain it like I am 8

Two kids are given the same seat number at the cinema. Either the cinema adds a little extra seat to that spot (both sit there), or it says "take the next empty seat". Either way, everyone gets a seat and can be found.

How it works, step by step

  1. A collision means two different keys hash to the same bucket. With more keys than buckets it is unavoidable (like pigeons sharing holes).
  2. Chaining: every bucket holds a list. Colliding keys join the list.
  3. Open addressing: every bucket holds at most one item. If the bucket is taken, try another bucket by a fixed rule (for example the next one, called linear probing).
  4. Lookups repeat the same rule: go to the hashed bucket, then check the list, or follow the probe path until you find the key or an empty bucket.
  5. A good hash function plus enough buckets (a low "load factor") keeps collisions rare and cheap.

The code in four languages

PHP

<?php
// Count how many names collide when 8 names are hashed into 7 buckets.
function hashKey(string $key, int $size): int {
    $h = 0;
    for ($i = 0; $i < strlen($key); $i++) $h = ($h * 31 + ord($key[$i])) % $size;
    return $h;
}

$names = ['Raju', 'Mira', 'Kabir', 'Zoya', 'Aarav', 'Bhaskar', 'Sharma', 'Asha'];
$size = 7;
$buckets = array_fill(0, $size, []);
foreach ($names as $n) $buckets[hashKey($n, $size)][] = $n;

$collisions = 0;
foreach ($buckets as $i => $list) {
    echo "bucket $i: " . ($list ? implode(', ', $list) : '-') . "\n";
    if (count($list) > 1) $collisions += count($list) - 1;   // everyone after the first collided
}
echo "collisions: $collisions of " . count($names) . " names\n";

JavaScript

// Count how many names collide when 8 names are hashed into 7 buckets.
function hashKey(key, size) {
  let h = 0;
  for (let i = 0; i < key.length; i++) h = (h * 31 + key.charCodeAt(i)) % size;
  return h;
}

const names = ['Raju', 'Mira', 'Kabir', 'Zoya', 'Aarav', 'Bhaskar', 'Sharma', 'Asha'];
const size = 7;
const buckets = Array.from({ length: size }, () => []);
for (const n of names) buckets[hashKey(n, size)].push(n);

let collisions = 0;
buckets.forEach((list, i) => {
  console.log('bucket ' + i + ': ' + (list.length ? list.join(', ') : '-'));
  if (list.length > 1) collisions += list.length - 1;   // everyone after the first collided
});
console.log('collisions: ' + collisions + ' of ' + names.length + ' names');

Java

import java.util.*;

public class Main {
    static int hashKey(String key, int size) {
        int h = 0;
        for (int i = 0; i < key.length(); i++) h = (h * 31 + key.charAt(i)) % size;
        return h;
    }

    public static void main(String[] args) {
        // Count how many names collide when 8 names are hashed into 7 buckets.
        String[] names = {"Raju", "Mira", "Kabir", "Zoya", "Aarav", "Bhaskar", "Sharma", "Asha"};
        int size = 7;
        List<List<String>> buckets = new ArrayList<>();
        for (int i = 0; i < size; i++) buckets.add(new ArrayList<>());
        for (String n : names) buckets.get(hashKey(n, size)).add(n);   // drop each name into its bucket

        int collisions = 0;
        for (int i = 0; i < size; i++) {
            List<String> list = buckets.get(i);
            System.out.println("bucket " + i + ": " + (list.isEmpty() ? "-" : String.join(", ", list)));
            if (list.size() > 1) collisions += list.size() - 1;   // everyone after the first collided
        }
        System.out.println("collisions: " + collisions + " of " + names.length + " names");
    }
}

Go

package main

import (
	"fmt"
	"strings"
)

func hashKey(key string, size int) int {
	h := 0
	for i := 0; i < len(key); i++ {
		h = (h*31 + int(key[i])) % size
	}
	return h
}

func main() {
	// Count how many names collide when 8 names are hashed into 7 buckets.
	names := []string{"Raju", "Mira", "Kabir", "Zoya", "Aarav", "Bhaskar", "Sharma", "Asha"}
	size := 7
	buckets := make([][]string, size)
	for _, n := range names {
		b := hashKey(n, size) // which bucket does this name hash to?
		buckets[b] = append(buckets[b], n)
	}

	collisions := 0
	for i, list := range buckets {
		text := "-"
		if len(list) > 0 {
			text = strings.Join(list, ", ")
		}
		fmt.Printf("bucket %d: %s\n", i, text)
		if len(list) > 1 {
			collisions += len(list) - 1 // everyone after the first collided
		}
	}
	fmt.Printf("collisions: %d of %d names\n", collisions, len(names))
}

Time: O(1) average · Extra space: O(n). With few collisions a lookup is one jump; with heavy collisions it degrades toward scanning a whole bucket.

Watch out for

  • Thinking collisions mean the hash function is "broken". They are expected, and the table just needs a plan for them.
  • Handling a collision on insert but forgetting the same rule when searching, so existing keys cannot be found.
  • Ignoring the load factor: when the table is almost full, collisions explode, so grow the table in time.

Quick check

  1. What is a hash collision?
    • A key that has no hash
    • Two different keys mapping to the same bucket
    • A full hash table
  2. Which are two common ways to handle collisions?
    • Chaining and open addressing
    • Sorting and searching
    • Pushing and popping
  3. Why can we not avoid collisions entirely?
    • Computers are slow
    • There are more possible keys than buckets
    • Hash functions are random