Algorithms Playbook
Data structureTime O(1) avg · Space O(n)8 min read

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?

Two Sum with a hash map
Example
Speed
0813211354752target = 9

seen (value → index)

{ }
1def two_sum(nums, target):
2 seen = {}
3 for i, x in enumerate(nums):
4 need = target - x
5 if need in seen:
6 return [seen[need], i]
7 seen[x] = i
8 return []
An empty hash map: it will remember every value we've passed and where.

Variables

i—
x—
need—
Step 1/18· Elements seen: 0
The array doesn't need to be sorted. We trade O(n) memory for the map to go from O(n²) (every pair) to a single O(n) pass.

Set or map?

You need…UseExample
Only "have I seen it?"Hash setContains duplicate
A value attached to each key (index, count, list)Hash mapTwo Sum, group anagrams
Counts of small known keys (letters a–z)An array of 26Valid anagram, fastest in practice
Keys in sorted orderA 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