Hash Map / Hash Set
Use when: O(1) lookup, frequency counting, complement search, grouping, detecting duplicates.
Signal words: two sum, anagram, duplicate, group by, count occurrences, seen before.
Common Uses
Complement Lookup (Two Sum pattern)
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = iFrequency Count
from collections import Counter
freq = Counter(nums)
# or
freq = {}
for x in nums:
freq[x] = freq.get(x, 0) + 1Grouping
from collections import defaultdict
groups = defaultdict(list)
for item in items:
key = get_key(item)
groups[key].append(item)Sliding Window with Hash Map
Track character counts in window; shrink when any count exceeds limit.
Key Questions
- What is the key? What is the value?
- Do I need count or just existence? (Counter vs Set)