Patterns: hash tables
This chapter 3 review covers three hash-table patterns: remembering what you have seen in a dict (two-sum in one pass), counting with Counter, and grouping with defaultdict(list), each turning an O(n²) comparison of every pair into O(n).
Two nested loops comparing every pair is the most common O(n²) there is: two-sum, finding duplicates, counting how often each word appears, putting anagrams together. A hash table swaps "compare with every earlier one" for "have I seen this?", O(1) on average, and the whole problem drops from O(n²) to O(n). At n = 100 000, comparing pairs is 5 billion steps; looking things up is 100 000. Most hash-table interview problems come down to three patterns: remember what you've seen (a dict: value → index), count (Counter) and group by a key (defaultdict(list)).
Pattern 1: remember what you've seen
Two-sum: in an unsorted nums, find two numbers that add up to target and return their indexes. Walk forward, writing each number you've seen into a dict (value → index). At x, the other half you need is target - x: if it appeared earlier, one lookup in the dict finds it.
| i | x | Looking for 13 − x | In seen? | Then |
|---|---|---|---|---|
| 0 | 6 | 7 | no | seen = {6: 0} |
| 1 | 1 | 12 | no | seen = {6: 0, 1: 1} |
| 2 | 9 | 4 | no | seen = {6: 0, 1: 1, 9: 2} |
| 3 | 4 | 9 | yes, index 2 | return (2, 3) |
Count both ways (400 numbers, the answer is the last two):
1def two_sum_brute(nums, target):2 looks = 03 for i in range(len(nums)):4 for j in range(i + 1, len(nums)):5 looks += 16 if nums[i] + nums[j] == target:7 return (i, j), looks8 return None, looks9 10def two_sum(nums, target):11 looks = 012 seen = {} # value -> index13 for i, x in enumerate(nums):14 looks += 115 if target - x in seen:16 return (seen[target - x], i), looks17 seen[x] = i18 return None, looks19 20nums = [(i * 7) % 398 * 2 for i in range(398)] + [1001, 1003]21print(two_sum_brute(nums, 2004))22print(two_sum(nums, 2004))23print(two_sum([6, 1, 9, 4, 8], 13))
((398, 399), 79800) ((398, 399), 400) ((2, 3), 4)
Brute force looked at 79800 pairs; the dict took 400 steps. The order matters: check first, then record. Record first and x can pair with itself: [3] looking for 6 would wrongly return (0, 0).
With repeated numbers, what does it print?
1def two_sum(nums, target):2 seen = {}3 for i, x in enumerate(nums):4 if target - x in seen:5 return seen[target - x], i6 seen[x] = i7 return None8 9print(two_sum([3, 3], 6), two_sum([3], 6), two_sum([1, 3, 3], 6))
[3, 3]: at i = 0 seen is still empty, so it records {3: 0}; at i = 1 it finds 3 and returns (0, 1). [3] has only one 3, and when it checks, that 3 hasn't been recorded yet, so None. [1, 3, 3] is (1, 2) the same way: check first, record after, and a number never pairs with itself.The same pattern also does: whether there is a duplicate (a set of what you've seen), the longest substring without repeats (a dict of where each character was last), subarrays summing to k (a dict counting how often each prefix sum appeared).
Following this stage's method (look for 8 − x first, then record x), find two numbers adding up to 8 in nums = [1, 6, 2, 5, 3]. Which pair of indices comes back?
(1, 2). 5 + 3 is 8 too, but the loop returns before getting there.Two sum done in one pass with a dict: what are the time and the extra space?
Two-sum
✓Finish two_sum(nums, target): nums is unsorted; return the indexes (i, j), i < j, of two numbers adding up to target, or None if there are none. One pass, with a dict of the numbers seen.
(0, 1) (1, 2) (0, 1) None
1def two_sum(nums, target):2 seen = {} # value -> index3 # check whether target - x has been seen first, then record x4 return None5 6print(two_sum([2, 7, 11, 15], 9))7print(two_sum([3, 2, 4], 6))8print(two_sum([3, 3], 6))9print(two_sum([1, 2], 7))
Pattern 2: counting
"How often does each word appear": in a dict the key is the word and the value the count. By hand it's counts[w] = counts.get(w, 0) + 1:
| Read | counts |
|---|---|
| the | {'the': 1} |
| cat | {'the': 1, 'cat': 1} |
| the | {'the': 2, 'cat': 1} |
| hat | {'the': 2, 'cat': 1, 'hat': 1} |
| the | {'the': 3, 'cat': 1, 'hat': 1} |
collections.Counter is a dict made for counting: hand it a sequence and the counting is done; a key never seen is 0 (no KeyError), and most_common(k) gives the k most common.
1from collections import Counter2 3text = "the cat and the hat and the bat sat on the mat"4words = text.split()5 6counts = {}7for w in words:8 counts[w] = counts.get(w, 0) + 19print(counts["the"], counts["and"])10 11c = Counter(words)12print(c["the"], c["dog"])13print(c.most_common(3))14print(sorted(c.items(), key=lambda kv: (-kv[1], kv[0]))[:3])
4 2
4 0
[('the', 4), ('and', 2), ('cat', 1)]
[('the', 4), ('and', 2), ('bat', 1)]
On equal counts, most_common keeps the order they first appeared (of the words seen once, cat came first; alphabetically it would be bat). When a problem says "equal counts in alphabetical order", sort it yourself with sorted: the key (-count, word) puts counts from high to low, then words from low to high.
Anagrams (the same letters in a different order, like listen and silent): count each word's letters and check the two Counters are equal, O(n). Sorting both and comparing also works, but it is O(n log n).
1from collections import Counter2 3def is_anagram(a, b):4 return Counter(a) == Counter(b)5 6print(is_anagram("listen", "silent"), is_anagram("aab", "abb"))7print(sorted("listen") == sorted("silent"))8print(sorted(Counter("aab").items()))
True False
True
[('a', 2), ('b', 1)]
Count the letters of "banana" with Counter. What does it print?
1from collections import Counter2 3c = Counter("banana")4print(c["a"], c["z"], c.most_common(2))
most_common(2) gives the top two, each as (letter, count).Checking whether two words of length n are anagrams: Counter(a) == Counter(b) versus sorted(a) == sorted(b). What does each cost?
The top k words
✓Finish top_k(words, k): return the k most common (word, count) pairs, counts from high to low; equal counts in alphabetical order of the word. Note that most_common orders equal counts by first appearance, which is not what is asked.
[('d', 4), ('a', 3)]
[('x', 2), ('y', 2)]
[('x', 2), ('y', 2), ('z', 1)]1from collections import Counter2 3def top_k(words, k):4 c = Counter(words)5 # sort by (-count, word) and take the first k6 return c.most_common(k)7 8print(top_k("b a c a b a d d d d".split(), 2))9print(top_k("y x y x z".split(), 2))10print(top_k("y x y x z".split(), 3))
Pattern 3: grouping by a key
Put anagrams into groups: eat, tea and ate in one, tan and nat in another, bat on its own. The trick is a key that every word in a group works out the same: sort the letters, and eat, tea and ate all become aet. Then defaultdict(list) drops each word into the bucket for its key:
1from collections import defaultdict2 3words = ["eat", "tea", "tan", "ate", "nat", "bat"]4groups = defaultdict(list)5for w in words:6 key = "".join(sorted(w))7 groups[key].append(w)8print(list(groups.values()))9print(groups["aet"], len(groups))10 11def letter_key(w):12 counts = [0] * 2613 for ch in w:14 counts[ord(ch) - ord("a")] += 115 return tuple(counts) # only a tuple can be a key16 17groups2 = defaultdict(list)18for w in words:19 groups2[letter_key(w)].append(w)20print(list(groups2.values()))
[['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']] ['eat', 'tea', 'ate'] 3 [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
defaultdict(list) puts an empty list in the first time it meets a key, so there's no if key not in groups to write. The second key is the counts of the 26 letters, O(k) to work out with no sorting; it has to be a tuple, since a list cannot be a key (this chapter's first lesson).
| Pattern | What the dict holds | Typical problems | Time |
|---|---|---|---|
| Remember what you've seen | value → index (or a set of values) | two-sum, any duplicates, longest substring without repeats | O(n) |
| Counting | thing → count (Counter) | top k most common, anagrams, first unique character | O(n) |
| Grouping by a key | worked-out key → list | grouping anagrams, sorting things into kinds | O(n) × the key |
In interviews: give brute force's O(n²) first, then "remember what I've seen in a dict, for O(n) time and O(n) space": trading space for time. For grouping, the key is one sentence saying clearly "which things should work out the same key".
Grouping anagrams: which of these can be the key in groups[...]?
sorted(w) gives a list, and a list can't be a dict key; join it into a string (or make it a tuple). len(w) and w[0] can be keys, but they would put words that aren't anagrams together, such as eat and bat.Group anagrams
✓Finish group_anagrams(words): put anagrams into groups. To make the output fixed, sort the words inside each group alphabetically, then sort the groups by their first word.
[['ate', 'eat', 'tea'], ['bat'], ['nat', 'tan']] [['a']] []
1from collections import defaultdict2 3def group_anagrams(words):4 groups = defaultdict(list)5 # the key: the word's letters sorted and joined6 return []7 8print(group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))9print(group_anagrams(["a"]))10print(group_anagrams([]))
How you write it at work
All three patterns have ready-made tools:
1from collections import Counter, defaultdict2 3c = Counter()4c.update(["a", "b", "a"])5c.update(["a"])6print(c["a"], c.most_common(1))7 8stock = Counter({"apple": 3, "pear": 1})9stock.subtract({"apple": 1})10print(sorted(stock.items()))11 12tags = defaultdict(set)13for user, tag in [("amy", "py"), ("bob", "go"), ("amy", "py"), ("amy", "sql")]:14 tags[user].add(tag)15print(sorted(tags["amy"]), len(tags))16 17d = {}18d.setdefault("k", []).append(1)19print(d, d.get("x", 0))
3 [('a', 3)]
[('apple', 2), ('pear', 1)]
['py', 'sql'] 2
{'k': [1]} 0
Counter(xs): counting;c[x]is 0 if missing;most_common(k)uses a heap inside, O(n log k);c.update(...)keeps counting.defaultdict(list),defaultdict(set),defaultdict(int): grouping, grouping without duplicates, counting.- A plain dict works too:
d.get(k, 0) + 1,d.setdefault(k, []).append(v). - Printing a set of strings, or output in a set's order, can change from run to run:
sortedfirst.
Count letters with defaultdict(int), then peek at a letter that never appeared. What does it print?
1from collections import defaultdict2 3d = defaultdict(int)4for ch in "hello":5 d[ch] += 16print(d["l"], d["z"], len(d))
d["z"] doesn't raise an error and returns 0, but it also puts "z": 0 into d: h, e, l, o plus z makes 5 keys. To peek without adding, use d.get("z", 0).Summary
Three hash-table patterns
- Remember what you've seen: a dict of value → index; check target − x, then record x; one pass, O(n)
- Counting: Counter, where a missing key is 0; for alphabetical ties, sorted(key=(-count, word))
- Grouping by a key: a group works out one key (sorted letters, a tuple of counts); defaultdict(list) collects them
- All of them spend O(n) space to replace the O(n²) of comparing pairs
1if target - x in seen: return seen[target - x], i2seen[x] = i3Counter(words).most_common(k)4groups["".join(sorted(w))].append(w)
Chapter 3 quick check
Five questions: hash functions, __eq__ and __hash__, linear probing, how many moves a resize makes, and Counter. Work out what each prints yourself, then pick an option.
The same polynomial hash with table size 31 and table size 7. What does it print?
1def h(s, m):2 v = 03 for c in s:4 v = (v * 31 + ord(c)) % m5 return v6 7print(h("ab", 31) == h("bb", 31), h("ab", 7) == h("ba", 7))
v * 31 % 31 is always 0, so every earlier letter is wiped out and only the last one is left: ab and bb both come down to b, equal. With size 7 position counts: ab is 3105 % 7 = 4 and ba is 3135 % 7 = 6, different.Only __eq__ is written. What does it print?
1class P:2 def __init__(self, x):3 self.x = x4 5 def __eq__(self, other):6 return self.x == other.x7 8a, b = P(1), P(1)9try:10 r = len({a, b})11except TypeError:12 r = "TypeError"13print(a == b, r)
__eq__ makes a == b True. But with only __eq__, Python sets __hash__ to None, so P objects cannot be hashed and putting them in a set raises TypeError. Write both: __hash__ returning hash(self.x).Linear probing, table size 7, putting in 3 10 17 4 in turn. What does it print?
1m = 72table = [None] * m3for k in [3, 10, 17, 4]:4 i = k % m5 while table[i] is not None:6 i = (i + 1) % m7 table[i] = k8print(table)
Separate chaining: once n exceeds the buckets, double and move all n. After 20 keys, what does it print?
1m, n, moves = 4, 0, 02for k in range(20):3 n += 14 if n > m:5 moves += n6 m *= 27print(m, moves)
Count the letters of mississippi. What does it print?
1from collections import Counter2 3c = Counter("mississippi")4print(c.most_common(2), c["z"])
most_common orders ties by first appearance: i comes before s. A key missing from a Counter is 0, not None, and there is no KeyError.