A hash table is the workhorse of practical programming — dict in Python, HashMap in Java, Map/objects in JS. It stores key → value pairs and gives you average O(1) insert, lookup, and delete. Half of all "optimize this" interview answers boil down to "use a hash map."
The magic is a hash function that turns any key into an array index. Instead of scanning for a key, you compute where it must live and jump straight there — trading a little memory and a good hash for near-constant time.
Collisions are inevitable
Many keys, finite buckets — by the pigeonhole principle two keys will eventually hash to the same slot. Two standard fixes:
- Separate chaining — each bucket holds a small list; colliding keys append to it (shown above).
- Open addressing — on collision, probe to the next open slot (linear/quadratic probing, double hashing). More cache-friendly, no pointers.
Why O(1) is "average"
If every key collides into one bucket, lookups degrade to O(n). Real implementations keep the load factor (items ÷ buckets) low by resizing, and use good hash functions, so worst cases are rare — but they exist (and hash-flooding attacks exploit them).
Load factor & resizing
When the load factor crosses a threshold (often ~0.75), the table doubles capacity and rehashes every key into the bigger array. That resize is O(n), but amortised across many inserts it keeps operations at O(1).
| Operation | Time |
|---|
Hash tables are unordered — if you need sorted keys, use a balanced BST / TreeMap (O(log n)).
The pattern that wins interviews
A hash map trades space for time: remember what you have seen so a second pass becomes a single lookup. Classic Two Sum drops from O(n²) to O(n).
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 []
}
Interview reflex
Hearing "count frequencies", "find duplicates", "seen before?", "group by", or "O(1) lookup"? Reach for a hash map (or a hash set when you only need membership).