Hash maps: the O(1) lookup that solves half of all interview problems
How a hash map finds a key in constant time, what it costs, and the classic move of trading memory for speed: Two Sum in one pass.
In short
A hash map stores key → value pairs and finds any key in O(1) on average. Whenever a loop keeps asking "have I seen this before?", a hash map usually turns O(n²) into O(n).
How it finds things instantly
A hash map is an array of buckets. A hash function turns the key into a number, and that number picks the bucket. Looking a key up means hashing it and going straight to its bucket: no scanning.
- Collisions: two keys can land in the same bucket. Buckets hold small lists (or probe the next slot), so lookups stay fast on average.
- Resizing: when it gets too full, the map doubles its buckets and rehashes everything. That's occasional O(n) work, but amortised it's still O(1) per insert.
- Worst case: if everything collides, lookups degrade to O(n). Good hash functions make that extremely unlikely.
The classic: Two Sum in one pass
Find two numbers that add up to a target, in an unsorted array. Instead of checking every pair, walk once and remember what you've seen. For each number, the question is: is target − x already in the map?
seen (value → index)
1def two_sum(nums, target):2 seen = {}3 for i, x in enumerate(nums):4 need = target - x5 if need in seen:6 return [seen[need], i]7 seen[x] = i8 return []
Variables
Set or map?
| You need… | Use | Example |
|---|---|---|
| Only "have I seen it?" | Hash set | Contains duplicate |
| A value attached to each key (index, count, list) | Hash map | Two Sum, group anagrams |
| Counts of small known keys (letters a–z) | An array of 26 | Valid anagram, fastest in practice |
| Keys in sorted order | A tree map (TreeMap, SortedDict) | O(log n) per operation |
Key takeaways
- 01Hash maps give O(1) average insert and lookup by hashing keys into buckets.
- 02"Have I seen this?" inside a loop is the signal to reach for a map or set.
- 03You trade O(n) memory for a big time win; say it out loud.
- 04Need order? Use a tree map (O(log n)); need small fixed keys? Use an array.
Check your understanding
1 of 3
What's the average time to look up a key in a hash map?
Related topics
Frequency counting
Walk the input once and keep a count per value in a hash map (or an array of 26 for letters). Comparing or querying counts replaces sorting and nested loops: O(n) time, O(k) space for k distinct values.
7 min read →Prefix sums
Build `prefix[i]` = sum of the first i numbers in O(n). Then the sum of `nums[l..r]` is `prefix[r+1] − prefix[l]`: O(1) per question instead of O(n).
7 min read →Two pointers
Put two indices in the array and move them by a rule so that every move rules out many candidates at once. Checking all pairs is O(n²); two pointers does it in one pass, O(n), with no extra memory.
8 min read →