Hash Maps & Sets for Problem Solving
Part of the Python Roadmap
In short
A huge share of interview problems have the same secret: instead of searching again and again, remember what you've seen in a dict or set. That one move turns slow O(n²) answers into fast O(n) ones.
Dicts and sets give average O(1) lookups, which turns many O(n²) brute-force solutions into O(n). They are the key to problems like two sum, anagram grouping and first non-repeating character.

Think of it like this
The society letterbox wall
In a Bengaluru apartment society, every flat has its own labelled letterbox. The postman doesn't search all 200 boxes; he reads "B-402" and goes straight there. A dict works the same way: the key's hash tells Python exactly which slot to look in.
Watch it happen
Two items that exactly match a ₹500 budget
1/5Find two prices that add up to 500. Keep a dict of price to index for everything seen so far.
The big ideas
What you need to know
dict: key to value
Store counts, positions or groups. Lookup, insert and update are O(1) on average.
set: have I seen it?
When you only need membership, a set is simpler and uses less memory than a dict.
Counter counts for you
collections.Counter("banana") gives {"a": 3, "n": 2, "b": 1} in one line.
defaultdict groups
defaultdict(list) lets you append to a key that doesn't exist yet. Perfect for grouping anagrams.
See it in code
Walk through the code
1from collections import Counter, defaultdict2 3 4def two_sum(prices: list[int], budget: int) -> tuple[int, int] | None:5 seen: dict[int, int] = {}6 for i, price in enumerate(prices):7 need = budget - price8 if need in seen:9 return seen[need], i10 seen[price] = i11 return None12 13 14def first_unique_char(s: str) -> str | None:15 counts = Counter(s)16 for ch in s:17 if counts[ch] == 1:18 return ch19 return None20 21 22def group_anagrams(words: list[str]) -> list[list[str]]:23 groups: defaultdict[str, list[str]] = defaultdict(list)24 for word in words:25 groups["".join(sorted(word))].append(word)26 return list(groups.values())27 28 29print(two_sum([150, 320, 90, 410, 230], 500)) # (2, 3)30print(first_unique_char("malayalam")) # y31print(group_anagrams(["listen", "silent", "rat", "tar", "art"]))1/4For each price, ask the dict whether its partner has already appeared. Store the price only after checking.
Three classic interview problems, each solved in O(n) time (anagram grouping also sorts each short word).
Save yourself the pain
Common mistakes
Oops
Storing the current price in seen before checking for its partner.
Do this instead
Check first, then store. Otherwise a budget of 300 with a single 150 would wrongly pair the item with itself.
Oops
Using a list as a dict key, like groups[sorted(word)].
Do this instead
Keys must be hashable. Convert with "".join(...) or tuple(...).
Oops
Counting with a manual if key in d: d[key] += 1 else: d[key] = 1 every time.
Do this instead
Use Counter, or d[key] = d.get(key, 0) + 1.
Your mission
Three warm-ups
Quick check
Why is checking need in seen fast when seen is a dict?
Go deeper
- 1Solve two sum with a dict in one pass.
- 2Group anagrams using sorted words as dict keys.
- 3Use Counter to compare character counts of two strings.
More topics at this stop
Stuck on this topic? Ask an Insider
Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.