Problem patterns with maps & sets
Turn O(n^2) brute-force searches into O(n) solutions using hash maps and sets.
By Invicly Tech, , in Data Structures & Algorithms. About 11 minutes to read.
In short
Many brute-force solutions compare every pair or rescan the input repeatedly. A hash map remembers what you have already seen, so each new element can be checked in O(1). Two-sum, grouping, frequency counting and prefix-sum counting all follow this idea.
Explained simply
Many slow solutions look like this: for every item, scan all the other items. That is O(n^2), and with 100,000 items it means 10 billion steps. Hashing patterns fix this by remembering things in a dict or set as you go. Then checking "have I seen this before?" takes O(1).
The classic example is two-sum: find two numbers that add up to a target. Instead of trying every pair, walk the list once. For each number x, ask: have I already seen target - x? If yes, you are done. If not, remember x and move on.
Another pattern is grouping. You compute a key for each item, such as the sorted letters of a word, and put items with the same key in the same list. All anagrams of 'listen' end up together, because they all sort to 'eilnst'.
Counting is the third pattern. A frequency map tells you how often each item appears. From it you can find duplicates, the most common items, or whether two strings use exactly the same letters.
The price is memory. You trade O(n) extra space for a big drop in time. In almost every interview and real program, that trade is worth it.
Press Play on a diagram to walk through it one step at a time.
- Step 1Read x at index i
Target t.
- Step 2Compute need
need = t - x
- Step 3Seen need?
Return its index and i.
- Step 4Remember x
seen[x] = i, then continue.
- Compare every pair
- O(n^2) time
- O(1) extra space
- 10^5 items: about 5 x 10^9 pairs
- Remember what you have seen
- O(n) average time
- O(n) extra space
- 10^5 items: 10^5 lookups
In depth
Complement maps: two-sum and friends
The pattern: while scanning, store something about earlier items in a dict, and for the current item compute exactly what partner it needs. If the partner is in the dict, you found a pair.
Order matters. Check first, then insert. If you insert x before checking, a target of 10 and x = 5 would pair 5 with itself. Checking first also handles duplicates correctly: for [5, 5] and target 10, the second 5 finds the first.
The same idea counts pairs. To count pairs with difference k, store counts of seen values and add count[x - k] + count[x + k] at each step (for k > 0). To count pairs whose sum is divisible by k, store counts of x % k and look up (k - x % k) % k. Python's % always returns a non-negative result for positive k, which keeps negative numbers simple.
- Check for the partner, then store the current item
- Store an index if you must return positions, a count if you only count
- Time O(n), space O(n)
Grouping by a canonical key
A canonical key is one normal form shared by every item that should be grouped together. Use a defaultdict(list) and append each item under its key.
For anagrams, the sorted string works: ''.join(sorted(w)). That costs O(L log L) per word of length L. For lowercase letters, a tuple of 26 counts is O(L) per word. Either key must be hashable, so use a str or tuple, never a list.
Other canonical keys: for shifted strings like 'abc' and 'bcd', use the tuple of gaps between neighbouring letters mod 26. For points on the same line through the origin, use the reduced fraction (dy // g, dx // g) with g = gcd(dy, dx) and a fixed sign. For files with the same content, use a hash of their bytes.
Total cost for n words: O(n L log L) with sorting, or O(n L) with counts.
- 'aet'
- eat
- tea
- ate
- 'ant'
- tan
- nat
- 'abt'
- bat
Frequency counting and top-k
collections.Counter builds a frequency map in O(n). From there, several questions become easy. Are two strings anagrams? Compare Counter(a) == Counter(b). What is the first unique character? Count, then scan the string again and return the first with count 1.
For the k most common items, Counter.most_common(k) uses a heap internally and runs in O(n log k). With no argument it sorts everything, O(n log n) for n distinct items.
There is an O(n) method called bucket sort by frequency. No item can appear more than n times, so make a list of n + 1 buckets where bucket f holds items seen f times. Walk the buckets from high to low until you have k items. This is a classic answer to "top k frequent elements" when the interviewer asks for better than O(n log n).
- Counter(a) == Counter(b) checks same multiset
- most_common(k): O(n log k)
- Bucket by frequency: O(n) top-k
Sets for duplicates, membership and sequences
Use a set when you only need yes or no. Contains duplicate: len(set(a)) < len(a), O(n). Duplicate within distance k: keep a set of the last k items, removing a[i - k] as you move, so the set never grows beyond k.
Longest consecutive sequence is a set classic. Put all numbers in a set. Only start counting from x if x - 1 is not in the set, because then x begins a run. From each start, count up while x + 1 is in the set. Each number is visited at most twice (once in the outer loop, once while counting a run), so the total is O(n), beating the O(n log n) sort-based answer.
For intersections, Python's a & b on sets is O(min(len(a), len(b))) on average, because it iterates over the smaller set and probes the larger.
Prefix sums plus a map
For subarray questions with a target, combine a running total with a dict of earlier totals. A subarray from i to j sums to k exactly when prefix[j+1] - prefix[i] = k. So at each step, look up how many earlier prefixes equal total - k.
Start the dict with {0: 1}. That represents the empty prefix and lets subarrays starting at index 0 be counted. To find the longest subarray with sum k instead of the count, store the first index where each total appeared and never overwrite it.
Many problems reduce to this. Equal numbers of 0s and 1s: replace each 0 with -1 and find the longest subarray with sum 0. Subarray sum divisible by k: store counts of total % k. Unlike a sliding window, this works when numbers are negative.
- 1Init
first = {0: -1}, total = 0, best = 0
- 2i=0..1
Totals 1, 0. Total 0 seen at -1: length 2.
- 3i=2
Total 3, first time: first[3] = 2.
- 4i=3
Total 0 again: length 3 - (-1) = 4.
- 5i=4
Total 2, new. Answer: 4, [1, -1, 3, -3].
Learn it in 5 short steps
About 40m each. Track them with a timer in your plan.
- 1Solve two-sum with a complement map~40m
- 2Group items by a computed key~40m
- 3Count frequencies and find top items~40m
- 4Use prefix sums with a hash map~40m
- 5Detect duplicates with a set~40m
Key points
- Two-sum drops from O(n^2) to O(n) time at the cost of O(n) space.
- Group anagrams by a canonical key such as the sorted string.
- Count subarrays summing to k by storing counts of prefix sums.
- Use a set when you only need membership, a dict when you need a value.
Key terms
Tap a card to flip it. 0/3 known
Examples
def two_sum(nums, target): # O(n) time, O(n) space
seen = {}
for i, x in enumerate(nums):
if target - x in seen:
return seen[target - x], i
seen[x] = i
def subarrays_sum_k(nums, k): # O(n)
counts, total, ans = {0: 1}, 0, 0
for x in nums:
total += x
ans += counts.get(total - k, 0)
counts[total] = counts.get(total, 0) + 1
return ansTop k frequent elements in O(n)
For [1, 1, 1, 2, 2, 3] and k = 2, count first: {1: 3, 2: 2, 3: 1}. Make buckets indexed by frequency 0 to 6. Put 1 in bucket 3, 2 in bucket 2, 3 in bucket 1. Walk from bucket 6 down and collect items until we have 2: we get 1, then 2. Every step is linear, so the whole thing is O(n).
from collections import Counter
def top_k(nums, k):
buckets = [[] for _ in range(len(nums) + 1)]
for x, f in Counter(nums).items():
buckets[f].append(x)
out = []
for f in range(len(nums), 0, -1):
for x in buckets[f]:
out.append(x)
if len(out) == k:
return out
return out
print(top_k([1, 1, 1, 2, 2, 3], 2)) # [1, 2]Longest consecutive sequence with a set
For [100, 4, 200, 1, 3, 2], put everything in a set. Check each number: 100 has no 99, so it starts a run of length 1. 4 has a 3, so skip it. 200 starts a run of 1. 1 has no 0, so it starts a run: 2, 3 and 4 are present, giving length 4. 3 and 2 are skipped. The answer is 4, in O(n) time.
def longest_consecutive(nums):
s = set(nums)
best = 0
for x in s:
if x - 1 not in s: # x starts a run
y = x
while y + 1 in s:
y += 1
best = max(best, y - x + 1)
return best
print(longest_consecutive([100, 4, 200, 1, 3, 2])) # 4Quick reference
- Two-sum: check target - x in seen, then seen[x] = i
- Group: defaultdict(list) keyed by a canonical form (sorted string or count tuple)
- Anagram check: Counter(a) == Counter(b), O(n)
- Top-k frequent: Counter.most_common(k) is O(n log k); frequency buckets are O(n)
- Subarray sum k: counts = {0: 1}; ans += counts[total - k]
- Longest run of consecutive ints: only start counting at x when x - 1 is absent
- Need only membership? Use a set. Need a value per key? Use a dict
Common mistakes
- Inserting x before checking, which pairs an element with itself.
- Forgetting the initial {0: 1} entry when counting prefix sums.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write first_unique(s) that returns the index of the first character that appears exactly once, or -1. Example: 'leetcode' returns 0, 'loveleetcode' returns 2, 'aabb' returns -1.
- Exercise 2medium
Write group_shifted(words) that groups strings that are letter shifts of each other. Example: ['abc', 'bcd', 'xyz', 'az', 'ba', 'a'] gives groups [abc, bcd, xyz], [az, ba], [a].
- Exercise 3hard
Write longest_balanced(bits) that returns the length of the longest contiguous subarray with equal numbers of 0s and 1s. Example: [0, 1, 0, 0, 1, 1, 0] returns 6.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- When should I sort instead of using a hash map?
- Sort when you need order (ranges, nearest values, or output in sorted order) or when memory is tight. Sorting costs O(n log n) time but can run in place, while a hash map gives O(n) time with O(n) extra space.
- Is defaultdict better than dict.get?
- They do the same job. defaultdict(list) or defaultdict(int) makes grouping and counting code shorter; dict.get(key, 0) is fine for one-off lookups and does not insert missing keys.
- Does using a set always make code faster?
- Membership tests drop from O(n) on a list to O(1) on average, which matters inside loops. For a handful of items, or a single check, building the set may cost more than it saves.