3.3.3Hashing

Chaining — linked lists in buckets, load factor, resizing

2,085 words9 min readdifficulty · medium

WHY does chaining exist?

WHY chaining specifically? Two key strategies exist:

  • Open addressing — store everything inside the array, probe for the next free slot.
  • Chaining — store a separate container (a linked list) per slot.

Chaining is chosen when we want: simple deletion, graceful behavior when the table gets crowded, and no clustering headaches.


WHAT is the structure?

Figure — Chaining — linked lists in buckets, load factor, resizing

HOW the operations work (let nn = number of stored keys):

Op What it does Cost
insert(k) compute h(k)h(k), prepend to list T[h(k)]T[h(k)] O(1)O(1)
search(k) compute h(k)h(k), scan list T[h(k)]T[h(k)] O(list length)O(\text{list length})
delete(k) search, then unlink the node O(list length)O(\text{list length})

Insert is O(1)O(1) because we prepend at the head (no need to check duplicates if we allow them, or O(len)O(\text{len}) if we must reject duplicates).


The Load Factor — the single most important number

Deriving the expected search cost (from scratch)


Resizing (Rehashing) — keeping α\alpha in check

WHY double, not add a constant? Doubling makes resizes exponentially rare.


Common Mistakes (Steel-manned)


Active Recall

Recall Predict before revealing (Forecast-then-Verify)
  1. Define load factor and state expected search cost.
    α=n/m\alpha=n/m; expected O(1+α)O(1+\alpha).
  2. Why double mm instead of adding a constant?
    → Geometric series gives O(1)O(1) amortized vs O(n)O(n).
  3. What's the worst case for a chained lookup and when?
    O(n)O(n), when all keys collide into one chain.
  4. Does chaining break at α=1\alpha=1?
    → No, only open addressing does; chaining degrades gracefully.
Recall Feynman: explain to a 12-year-old

Imagine a wall of mailboxes numbered 0–9. A rule (the hash) tells each letter which box it belongs to. Sometimes two letters go to the same box — so inside each box you keep a little string of letters clipped together (the linked list). To find a letter, go to its box and flip through that small string. If boxes get too crowded (too many letters per box on average — that's the load factor), you buy a bigger wall with twice as many boxes and re-sort all the letters so each box is light again. Light boxes = fast finding.


Connections

  • Hash Functions — quality of hh decides whether uniform-hashing assumption holds.
  • Open Addressing — the alternative (linear/quadratic probing, dies at α=1\alpha=1).
  • Amortized Analysis — justifies O(1)O(1) inserts despite occasional O(m)O(m) resizes.
  • Dynamic Arrays — same doubling trick for amortized O(1)O(1) append.
  • Pigeonhole Principle — why collisions are unavoidable.
  • Linked Lists — the bucket data structure itself.

What is the load factor of a hash table?
α=n/m\alpha = n/m, the average number of keys per bucket (nn keys, mm buckets).
Expected cost of search in a chained hash table?
O(1+α)O(1+\alpha) under simple uniform hashing.
Worst-case cost of search in a chained hash table and when does it happen?
O(n)O(n), when every key hashes to the same bucket (one long chain).
Why double the table size on resize instead of adding a fixed number of slots?
Doubling makes total rehash work a geometric series 2n\le 2n, giving O(1)O(1) amortized insert; constant growth gives Θ(n2)\Theta(n^2) total → Θ(n)\Theta(n) per insert.
What does rehashing involve?
Allocating a larger array (e.g. 2m2m) and recomputing h(k)modmh(k)\bmod m' for every key, re-inserting all of them.
Does chaining stop working at α=1\alpha=1?
No — only open addressing fills up at α=1\alpha=1; chaining keeps working and just slows down linearly in α\alpha.
Why is insertion (without duplicate check) O(1)O(1) in chaining?
You compute the hash and prepend the node at the head of the bucket's list.
What assumption gives expected O(1+α)O(1+\alpha)?
Simple Uniform Hashing: each key is equally and independently likely to hash to any of the mm slots.
Typical resize trigger threshold?
When α\alpha exceeds a chosen max like 0.750.75.
Expected length of any single bucket?
n1m=αn \cdot \frac{1}{m} = \alpha.

Concept Map

since U bigger than m

forces

handled by

or by

structure is

supports

avg length equals

assumption gives

scan cost

search cost

bound a to stay fast

Hash function h maps keys to slots

Pigeonhole principle

Collisions unavoidable

Chaining

Open addressing

Linked list per bucket

Insert search delete

Load factor a equals n over m

Simple uniform hashing

Expected cost O of 1 plus a

Keep a bounded so O of 1

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, hash table ek array hota hai jisme ek hash function key ko ek index pe map karta hai. Problem ye hai ki do alag keys kabhi-kabhi same index pe aa jaati hain — isko collision kehte hain, aur ye unavoidable hai (pigeonhole principle). Chaining ka simple jugaad: har bucket (index) pe ek linked list rakho. Jo bhi keys us index pe hash hoti hain, sab us list me clip ho jaati hain. Search karte time bas us chhoti si list ko scan karo.

Sabse important number hai load factor α=n/m\alpha = n/m — yani average kitni keys per bucket. Expected search cost nikalti hai O(1+α)O(1+\alpha): "1" matlab hash compute karna aur ek bucket touch karna, "α\alpha" matlab average itne items walk karna. Agar α\alpha ko chhota constant (jaise 0.75) ke neeche rakho, to har operation expected O(1)O(1) rehta hai — yahi pura magic hai. Worst case me agar saari keys ek hi bucket me chali jaayein to O(n)O(n) ho jaata hai, isliye accha hash function zaroori hai.

Jaise-jaise keys badhti hain, nn badhta hai aur α\alpha bada hone lagta hai — chains lambi ho jaati hain. Isliye resizing (rehashing) karte hain: jab α\alpha threshold cross kare, array ka size double kar do aur saari keys naye mm ke hisaab se dobara hash karke daal do. Double kyun? Kyunki doubling se total copy-work geometric series ban jaata hai (1+2+4+<2n1+2+4+\dots < 2n), isliye per-insert cost amortized O(1)O(1) rehta hai. Agar tum constant (jaise +10) add karte to total kaam Θ(n2)\Theta(n^2) ho jaata — disaster. Bas yaad rakho: collisions → alpha → chain length → resize.

Go deeper — visual, from zero

Test yourself — Hashing

Connections