Solving with dicts
Implement the count and group patterns in Python, then solve the classic two-sum problem with O(n) dict lookup.
- Implement the count pattern using a dict
- Implement the group pattern using a dict
- Solve two-sum using a dict for O(n) lookup
Key-value thinking described two patterns. Now let's implement them in Python, then apply the same idea to a problem where it matters a great deal: two-sum.
The three functions
Read each function carefully before running. Predict the output, then run and check yourself.
Why the dict makes two-sum fast
The brute-force approach to two-sum is a pair of nested loops: for each element, scan the rest of the list looking for its complement. That is O(n²) — at n=10 000 it means roughly 100 million comparisons.
The dict approach does one pass. At each index i, the question is: "have I
already seen target - nums[i]?" The seen dict answers that in O(1). So the
whole function is O(n) — linear in the length of the list.
This is the general trade: spend O(n) space on a dict so that membership checks drop from O(n) to O(1). Whenever you catch yourself writing a loop that searches a list you've already processed, stop and ask whether a dict would remove the inner scan entirely.
dict.get(key, default) avoids a KeyError when the key is absent — it
returns default instead. counts.get(word, 0) + 1 is the idiomatic way to
increment a counter that may not exist yet.
Where to go next
Next: Big-O intuition — a precise vocabulary for talking about how fast (or slow) an algorithm grows as the input gets larger.