The hash map pattern: how to spot it
Updated
A hash map trades memory for time: remember what you have seen, keyed by the thing you will look up later, and a nested loop becomes one pass. Most interview problems use it for one of three jobs: finding a partner value, counting, or grouping.
When to reach for it
- You would otherwise compare every pair, and the pair is defined by a value you can compute (a complement, a difference, a key).
- The question is about how many times something appears, or whether two things have the same counts.
- Items that share some property need to end up together, and you can turn that property into a key.
- The input is unsorted and sorting it would lose the original indexes you need to return.
The usual shape
seen = {}
for i, x in enumerate(items):
want = partner_of(x) # e.g. target - x
if want in seen:
return seen[want], i
seen[x] = i # store after checking, so x can't pair with itself3 LeetCode hash maps problems, easiest first
- Two Sum easy
One pass: store what you have seen, query the complement.
- Valid Anagram easy
Same letters iff the two frequency maps are equal.
- Group Anagrams medium
The anagram key is the grouping key. Do not overwrite the list under it.
Skills these problems use
Each one has a free lesson with worked examples and a drill.
- Two-sum with a value-to-index map
- Check whether a map contains a key
- Get the value for a key
- Build a frequency map
- Compare two frequency maps
- Group values by a key
- Append to a list under a key
check which skills you have 10 minutes, free, no account.