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 / case | Cost | Notes |
|---|---|---|
| Insert / lookup / delete (average) | O(1) | the headline feature |
| Worst case (all keys collide) | O(n) | pathological; seeded hashes prevent it |
| Resizing | O(n) amortized O(1) | happens ~when load factor > 0.75 |
| Space | O(n) | bucket array + entries |
| Ordered iteration | O(n log n) | hash tables are UNORDERED, sort keys yourself; use Map for insertion order |
Hash maps in action: two classic speedups
// 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) averagePractice
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).