Hash Maps
Key-value lookups in O(1) on average - the fastest way to remember what you’ve seen.
- active this step
- visited / done
- result
Start with an empty map
seen will map each value to its index.
VARIABLES
- i
- -
- need
- -
- seen
- {}
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
A hash map (a Python dict) stores key-value pairs and finds a key by hashing it to a bucket. A set is the keys-only version.
Why it matters
Spending O(n) memory for O(1) lookups turns many O(n²) searches into a single pass.
Think of it like this
A coat check: hand over your ticket number and get your coat back without searching every hanger.
Use it when
- Counting frequencies
- Finding a complement or pair in one pass
- Grouping items by a computed key
Avoid it when
- You need keys in sorted order - use a sorted list or a tree
- Memory is extremely limited
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| Insert, lookup or delete | O(1) average | O(n) total |
| Worst case (many collisions) | O(n) | - |
| Iterate over all keys | O(n) | O(1) |
Often confused with: two pointers - solves pair sums with O(1) memory, but needs sorted input.
How to recognize it
Clues in interview prompts that point straight to this pattern.
- “Return the indices” plus unsorted input points to a dict of value to index
- Lists can’t be keys; convert them to tuples
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- Storing x before checking - 3 + 3 = 6 would wrongly return [0, 0]
- Using a list for membership checks (O(n) each)
- Assuming dict order means sorted order - it’s insertion order
Edge cases to test
- Duplicates like [3, 3] with target 6
- Negative numbers and zero
- No valid pair
Knowledge check
Quick check to lock in the intuition.
For nums = [3, 3] and target 6, why check the map before storing?
Practice
Apply what you just watched on real interview problems.