Hash Maps
Trade memory for speed. Turn O(n) searches into O(1) lookups. The single most versatile data structure in interview problems.
"Does this value exist?" — O(n) scan vs O(1) lookup
The insight: a hash function maps any key to an integer index in O(1). Python's dict gives you a lookup table where key in d and d[key] are both O(1). Use this to eliminate inner loops entirely.
The Two HashMap Patterns
Every HashMap problem uses one of these two patterns. Identify which before writing code.
Store a value and where you've seen it. At each step, check if the complement/partner already exists in the map. Enables O(1) 'have I seen X before?' queries.
Store a value and how many times you've seen it. Use frequencies to check anagrams, find unique chars, build palindromes, count occurrences.
The 3-Step HashMap Framework
The same three steps work for every HashMap problem.
Decide: index map (value → index) or frequency counter (value → count)? Initialize an empty dict or Counter before any loop.
seen = {} # index map
freq = Counter(s) # frequency counterFor index maps: check if the complement exists BEFORE storing the current element. This avoids matching an element with itself and ensures correct index pairs.
if complement in seen: # query first
return [seen[complement], i]
seen[num] = i # then storeFor frequency counters: after building the map, make a second pass to analyze it. Count chars with even/odd frequency, find the first unique, compare two maps.
for ch, count in freq.items():
if count % 2 == 0:
result += countPattern Recognition
30-second diagnosis: does this need a HashMap?