core pattern
Hash Map / Set
Use hash maps for O(1) lookups to track frequencies, find duplicates, store complements, or establish relationships between elements.
Time
O(n)
Space
O(n)
🧠Mental Model
“A librarian with perfect memory — instantly retrieves any book by its catalog number.”
Verbal cue: Store what you've seen, lookup in O(1)
🎯Recognition Triggers
When you see these patterns in a problem, consider this approach:
Count occurrencesFind duplicateTwo sum (unsorted)Group by propertyCheck if exists in O(1)Anagram detectionSubarray sum equals K
💡Interview Tips
- 1Hash map trades space for time — mention this tradeoff
- 2Clarify what to return: indices, values, or boolean
- 3For frequency problems, collections.Counter (Python) is useful
- 4Consider sorted alternatives when space is critical
⚠️Common Mistakes
- ✕Not considering hash collisions in theoretical analysis
- ✕Forgetting to store the value AFTER checking (for two-sum)
- ✕Using wrong hash function for custom objects
- ✕Not handling case when element equals its complement