Chaining
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Chaining is a collision rule where every slot of a hash table holds a small list. If two keys land in the same slot, both simply sit in that list. To find something you jump to the slot and look through only that short list.
Practical use cases
- Web app: Session store for logged-in users. A web server keeps thousands of login sessions in memory, looked up by session id from each request cookie. Several ids share a slot, so each slot keeps a short list of sessions. Every page load finds its user in one jump plus a glance at two or three entries, so 10,000 users never slow each other down.
- Web app: Spell checker in a text editor. A blog editor underlines misspelled words as you type. All dictionary words sit in a table where each slot holds the few words that hashed there. Checking a word costs one jump and a short scan, so a 200,000-word dictionary is checked in a blink instead of being read from A to Z.
- System: Java HashMap buckets. Java HashMap is a well-known example of this idea: each bucket holds a linked list of entries. When a bucket grows very long, newer versions turn it into a tree so lookups stay fast even under heavy collisions. Short lists inside each slot are a cheap price for never losing an entry.
The story: The Tiffin Dabba Rack
In Mumbai, the dabbawalas carry thousands of lunch boxes every day, and the system is built on codes. At the Dadar station sorting rack, each hook belongs to one destination code. Now picture a smaller version at Mira's uncle's office: five hooks and ten tiffins arriving.
The hooks quickly ran out of single spots. A clumsy assistant tried to push a tiffin on an already-full hook and it clattered to the floor. Uncle then found a simple fix: instead of a hook holding one tiffin, give every hook a string that can carry many. Tiffins for the same hook are tied one after another on a string, in the order they arrived.
To find Kabir's tiffin, the helper did not search all five hooks. He used the office code to go to one hook, then walked along that one short string, reading name tags. That is chaining: each bucket is a linked chain of everything that hashed to it. Because the chains stay short when the hook count is sensible, finding a tiffin is still almost instant.
How to spot this problem, and where you need it
You need fast lookups by key, and keys will sometimes share a slot. You want a simple, forgiving way to store the extras without moving other data around.
Signs you need it
- You need to add and delete keys all the time, and you do not want to shuffle other entries when a slot is already taken.
- You cannot predict how many keys will arrive, so slots may hold one, five, or zero items.
- The problem statement mentions "buckets", "linked list per index" or "separate chaining".
- You catch yourself writing array-of-arrays code like table[index][] = item in PHP to group things by a computed number.
Where to use it in a project
- Writing a custom in-memory index for a feature such as autocomplete words grouped by first letters or a hashed key.
- Understanding how PHP arrays, JavaScript Map and Java HashMap behave internally when millions of keys are added.
The solution
Make an array of slots, and let each slot start as an empty list. To insert, compute the hash of the key to pick a slot and add the item to that slot list. To search, compute the same hash, go to that slot, and look through only its short list. To delete, remove the item from that list. If the lists get long on average, make the table bigger and re-spread the keys.
Payoff: Before: scanning 200,000 words per check. After: one jump and about 2 comparisons, so typing feels instant.
Explain it like I am 8
Each cubby at school has a long ribbon hanging from it. When two kids share a cubby, their bags are both tied on the ribbon. To find your bag, you go to your cubby and look along the ribbon, not all around the room.
How it works, step by step
- Make an array of buckets. Each bucket starts as an empty list.
- put(key, value): hash the key to find the bucket. Walk that list: if the key is already there, update its value. Otherwise add a new pair at the end.
- get(key): hash the key, then walk only that bucket's list looking for the key.
- remove(key): find the pair in the bucket's list and take it out. Other items stay put.
- Keep an eye on the average chain length. If it grows, add more buckets and re-hash everything ("resizing").
The code in four languages
PHP
<?php
class ChainedHashMap {
private array $buckets;
public function __construct(private int $size = 5) {
$this->buckets = array_fill(0, $size, []); // empty chain in every bucket
}
private function hash(string $key): int {
$h = 0;
for ($i = 0; $i < strlen($key); $i++) $h = ($h * 31 + ord($key[$i])) % $this->size;
return $h;
}
public function put(string $key, $value): void {
$b = $this->hash($key);
foreach ($this->buckets[$b] as $i => $pair) {
if ($pair[0] === $key) { $this->buckets[$b][$i][1] = $value; return; } // update
}
$this->buckets[$b][] = [$key, $value]; // add to chain
}
public function get(string $key) {
foreach ($this->buckets[$this->hash($key)] as [$k, $v]) {
if ($k === $key) return $v;
}
return null;
}
public function remove(string $key): bool {
$b = $this->hash($key);
foreach ($this->buckets[$b] as $i => $pair) {
if ($pair[0] === $key) {
array_splice($this->buckets[$b], $i, 1); // cut from chain
return true;
}
}
return false;
}
}
$m = new ChainedHashMap();
$m->put('Kabir', 'class 7');
$m->put('Zoya', 'class 6'); // shares bucket 4 with Kabir
echo $m->get('Zoya') . "\n"; // class 6
$m->remove('Kabir');
echo $m->get('Zoya') . "\n"; // class 6 (still there)
echo var_export($m->get('Kabir'), true) . "\n"; // NULL
$m->put('Zoya', 'class 7'); // update
echo $m->get('Zoya') . "\n"; // class 7
JavaScript
class ChainedHashMap {
constructor(size = 5) {
this.size = size;
this.buckets = Array.from({ length: size }, () => []); // empty chain in every bucket
}
hash(key) {
let h = 0;
for (let i = 0; i < key.length; i++) h = (h * 31 + key.charCodeAt(i)) % this.size;
return h;
}
put(key, value) {
const chain = this.buckets[this.hash(key)];
for (const pair of chain) {
if (pair[0] === key) { pair[1] = value; return; } // update
}
chain.push([key, value]); // add to chain
}
get(key) {
for (const [k, v] of this.buckets[this.hash(key)]) {
if (k === key) return v;
}
return null;
}
remove(key) {
const chain = this.buckets[this.hash(key)];
const i = chain.findIndex(pair => pair[0] === key);
if (i === -1) return false;
chain.splice(i, 1); // cut from chain
return true;
}
}
const m = new ChainedHashMap();
m.put('Kabir', 'class 7');
m.put('Zoya', 'class 6'); // shares bucket 4 with Kabir
console.log(m.get('Zoya')); // class 6
m.remove('Kabir');
console.log(m.get('Zoya')); // class 6 (still there)
console.log(m.get('Kabir')); // null
m.put('Zoya', 'class 7'); // update
console.log(m.get('Zoya')); // class 7Java
import java.util.*;
public class Main {
static class Entry {
String key;
String value;
Entry(String key, String value) { this.key = key; this.value = value; }
}
static class ChainedHashMap {
private final List<List<Entry>> buckets = new ArrayList<>();
private final int size;
ChainedHashMap(int size) {
this.size = size;
for (int i = 0; i < size; i++) buckets.add(new ArrayList<>()); // empty chain in every bucket
}
private int hash(String key) {
int h = 0;
for (int i = 0; i < key.length(); i++) h = (h * 31 + key.charAt(i)) % size;
return h;
}
void put(String key, String value) {
List<Entry> chain = buckets.get(hash(key));
for (Entry e : chain) {
if (e.key.equals(key)) { e.value = value; return; } // update
}
chain.add(new Entry(key, value)); // add to chain
}
String get(String key) {
for (Entry e : buckets.get(hash(key))) {
if (e.key.equals(key)) return e.value;
}
return null;
}
boolean remove(String key) {
List<Entry> chain = buckets.get(hash(key));
for (int i = 0; i < chain.size(); i++) {
if (chain.get(i).key.equals(key)) {
chain.remove(i); // cut from chain
return true;
}
}
return false;
}
}
public static void main(String[] args) {
ChainedHashMap m = new ChainedHashMap(5);
m.put("Kabir", "class 7");
m.put("Zoya", "class 6"); // shares bucket 4 with Kabir
System.out.println(m.get("Zoya")); // class 6
m.remove("Kabir");
System.out.println(m.get("Zoya")); // class 6 (still there)
System.out.println(m.get("Kabir")); // null
m.put("Zoya", "class 7"); // update
System.out.println(m.get("Zoya")); // class 7
}
}Go
package main
import "fmt"
type pair struct {
key string
value string
}
type ChainedHashMap struct {
buckets [][]pair // empty chain in every bucket
size int
}
func NewChainedHashMap(size int) *ChainedHashMap {
return &ChainedHashMap{buckets: make([][]pair, size), size: size}
}
func (m *ChainedHashMap) hash(key string) int {
h := 0
for i := 0; i < len(key); i++ {
h = (h*31 + int(key[i])) % m.size
}
return h
}
func (m *ChainedHashMap) Put(key, value string) {
b := m.hash(key)
for i := range m.buckets[b] {
if m.buckets[b][i].key == key {
m.buckets[b][i].value = value // update
return
}
}
m.buckets[b] = append(m.buckets[b], pair{key, value}) // add to chain
}
func (m *ChainedHashMap) Get(key string) (string, bool) {
for _, p := range m.buckets[m.hash(key)] {
if p.key == key {
return p.value, true
}
}
return "", false
}
func (m *ChainedHashMap) Remove(key string) bool {
b := m.hash(key)
for i, p := range m.buckets[b] {
if p.key == key {
m.buckets[b] = append(m.buckets[b][:i], m.buckets[b][i+1:]...) // cut from chain
return true
}
}
return false
}
func main() {
m := NewChainedHashMap(5)
m.Put("Kabir", "class 7")
m.Put("Zoya", "class 6") // shares bucket 4 with Kabir
v, _ := m.Get("Zoya")
fmt.Println(v) // class 6
m.Remove("Kabir")
v, _ = m.Get("Zoya")
fmt.Println(v) // class 6 (still there)
if _, ok := m.Get("Kabir"); !ok {
fmt.Println("null") // gone
}
m.Put("Zoya", "class 7") // update
v, _ = m.Get("Zoya")
fmt.Println(v) // class 7
}Time: O(1) average, O(n) worst · Extra space: O(n + buckets). Average chain length is items divided by buckets, so a sensible table keeps chains short; if everything lands in one bucket you must walk all n.
Watch out for
- Appending a new pair without first checking whether the key already exists, creating duplicate keys.
- Never resizing: with a fixed 5 buckets and a million keys, every chain is huge.
- Removing an element from a list while looping over it without care (skipping the next item).
Quick check
- In chaining, what does each bucket hold?
- Exactly one item
- A list of all items that hashed there
- The hash function
- To find a key, how much of the table do you search?
- Only the chain in the key's bucket
- Every bucket
- The first half
- What makes chaining slow?
- Too many empty buckets
- Very long chains, because too many keys share buckets
- Using strings as keys