pattern_drill
Role
Full set incl. design-adjacent patterns
Patterns
Counting & grouping

Hashmap

Recognition triggers

  • Need O(1) lookup of complements or seen values
  • Count frequencies of items
  • Group items by a derived key (sorted letters, hash)
  • 'Find duplicates / find pair' in unsorted data

Core idea

Trade space for time. Use a dict to remember what you've seen, what its count is, or which bucket it belongs to.

Reusable template

python
from collections import defaultdict, Counter

def solve(arr):
    seen = {}              # value -> index / data
    for i, x in enumerate(arr):
        if key(x) in seen:
            return ...     # use the match
        seen[key(x)] = i
    return ...

Worked example

Problem

Two Sum (unsorted): return indices of two numbers summing to target.

Examples
in nums = [2, 7, 11, 15], target = 9
out [0, 1]
nums[0] + nums[1] == 9
in nums = [3, 2, 4], target = 6
out [1, 2]
in nums = [3, 3], target = 6
out [0, 1]
Try to sketch the solution from the template first.