Arrays & Hashing
Signal: "find a duplicate", "have we seen X before?", "count occurrences", "group things that are equivalent", or any brute force that looks like for each element, scan all others.
Core idea: a hash set or hash map gives average O(1) insert and lookup, so a nested O(n²) scan becomes a single O(n) pass that remembers what it has seen. The price is O(n) extra memory.
Templates
# 1) Seen-before check
seen = set()
for x in nums:
if x in seen: # O(1) average
... # found a repeat / complement
seen.add(x)
# 2) Frequency counting
from collections import Counter
freq = Counter(nums) # {value: count}
# 3) Grouping by a canonical key
from collections import defaultdict
groups = defaultdict(list)
for item in items:
groups[canonical(item)].append(item)Choosing the key
The trick in many problems is the canonical key: sorted letters for anagrams, a (dx, dy) slope for collinear points, a tuple of counts. Ask yourself: what do all equivalent items have in common, and how can I make it hashable?
Mention the trade-off out loud: "I'll use O(n) extra memory to get O(n) time. If memory were tight, I could sort in place for O(n log n) and O(1) extra space."