All patterns
HashMap / Frequency Map
Trade memory for O(1) average lookups.
time O(n) averagespace O(n)
What it is
Store what you have already seen (values, counts, indices, prefix sums) so a later step can answer “have I seen the complement?” without rescanning.
When to reach for it
- Find a pair or complement
- Count occurrences, group by key
- Detect duplicates
- Repeated membership queries on a list
Clues in the problem
- Inner loop only searches for a value
- list.contains or indexOf inside a loop
- Unsorted input where indices matter
Template
def two_sum(a, target):seen = {} # value -> indexfor i, x in enumerate(a):if target - x in seen:return seen[target - x], iseen[x] = ireturn None
Practice problems
- Two Sum
- Group Anagrams
- Contains Duplicate
- Subarray Sum Equals K
- Longest Consecutive Sequence
Common mistakes
- Inserting before checking, so an element pairs with itself
- Assuming O(1) worst case; hashing is average-case
- Using floating point or mutable objects as keys