DSA & CS / 2. HASH MAPS & SETS
Hash Maps & Sets
O(1) lookup — the most versatile tool in your arsenal
EXPLANATION
A Hash Map (dict in Python) maps keys to values using a hash function. Average O(1) for insert, lookup, delete. Worst case O(n) due to collisions, but rare. Hash Set is a hash map where you only care about keys (values are irrelevant). O(1) membership testing. When to reach for a hash map: • Counting frequencies → Counter or defaultdict(int) • Grouping items → defaultdict(list) • Checking if element seen before → set • Caching computed results → dict (manual memoization) • Two Sum / complement problems → store seen values The classic trick: instead of nested loop to find pairs, store what you've seen in a hash map and check if the complement exists in O(1). Python tools: • dict → general hash map • defaultdict → auto-initializes missing keys • Counter → frequency counting with extras (most_common, etc.) • set → O(1) membership, union, intersection
DIAGRAM
Hash Map internal:
key → hash(key) % bucket_count → bucket index
"apple" → hash("apple") % 8 → bucket 3 → value: 5
Collision: two keys → same bucket → chaining (linked list)
Counter use case — anagram check:
"listen" → {l:1, i:1, s:1, t:1, e:1, n:1}
"silent" → {s:1, i:1, l:1, e:1, n:1, t:1}
same Counter → anagram ✓
Two Sum trick:
seen = {}
for each num: if (target - num) in seen → found pair
else: seen[num] = indexCODE