Skip to main content
Intermediate ~16 min read

Hash Tables & Sets

Average O(1) lookup: how hashing works, what collisions are, load factors, and when hash tables are the wrong tool.

Prerequisites: Arrays: Traversal, Insertion & Deletion, Big O Notation & Time Complexity

A hash table (JavaScript's Map/Object, Python's dict) answers "have I seen this key?" in constant time on average. The trick: a hash function converts the key into a number, modulo the bucket count, and that number IS the array index. No searching at all, the key computes its own storage address. Insert, lookup, and delete are all O(1) average.

The fine print: two keys can hash to the same index, a collision. Real hash tables resolve collisions (chaining: a linked list per bucket; open addressing: probe the next free slot) and track their load factor (elements ÷ buckets). Past a threshold (commonly 0.75) they resize, rehashing every element into a bigger bucket array, an O(n) operation amortized over all the cheap operations that preceded it. The pathological worst case (all keys collide) is O(n) per operation, which is why adversarial hash-flooding attacks exist and why languages seed their hash functions.

Operation / caseCostNotes
Insert / lookup / delete (average)O(1)the headline feature
Worst case (all keys collide)O(n)pathological; seeded hashes prevent it
ResizingO(n) amortized O(1)happens ~when load factor > 0.75
SpaceO(n)bucket array + entries
Ordered iterationO(n log n)hash tables are UNORDERED, sort keys yourself; use Map for insertion order

Hash maps in action: two classic speedups

hash-patterns.js
// 1) Two-sum in O(n): remember what you've seen
function twoSum(nums, target) {
  const seen = new Map();               // value → index
  for (let i = 0; i < nums.length; i++) {
    const need = target - nums[i];
    if (seen.has(need)) return [seen.get(need), i];
    seen.set(nums[i], i);
  }
  return null;
}   // was O(n²) with nested loops, the map replaces the inner loop

// 2) Frequency counting
function firstUniqueChar(s) {
  const counts = new Map();
  for (const ch of s) counts.set(ch, (counts.get(ch) ?? 0) + 1);
  for (let i = 0; i < s.length; i++) if (counts.get(s[i]) === 1) return i;
  return -1;
}

// 3) Set semantics: membership + dedupe
const seen = new Set();
seen.add(5);
seen.has(5);   // true, O(1) average

Practice

nums = [4, 7, 2, 9], target = 11. Trace twoSum: after processing index 2 (value 2), what does the map contain, and what happens at index 3?

Reveal explanation

Index 0: add 4→0. Index 1: add 7→1. Index 2: need 9 (absent), add 2→2. Index 3: value 9, need 2, present! Return [2, 3]. One pass, O(n).

Check your understanding

  1. 1.What makes hash table lookup O(1) on average?
  2. 2.A hash table with 8 buckets holds 12 items. Its load factor is 1.5. What typically happens next?
  3. 3.You must repeatedly query "how many orders were placed in this date range?" Which structure fits best?

Finished reading?

Mark it complete to earn +50 XP. Progress stays in your browser.

Keep going