Kodewick
Start learning →
Patterns: hash tables21 / 52

Patterns: hash tables

Lesson 21 of 52 · Part 4 · Hash tables: dict and set · about 20 minutes

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.

ixLooking for 13 − xIn seen?Then
067noseen = {6: 0}
1112noseen = {6: 0, 1: 1}
294noseen = {6: 0, 1: 1, 9: 2}
349yes, index 2return (2, 3)
nums = [6, 1, 9, 4, 8], target = 13: each step first checks whether 13 − x has been seen, and only then records x

Count both ways (400 numbers, the answer is the last two):

main.py
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))
Output
((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).

Guess the outputA wrong guess is fine

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))

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).

Choose one

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?

Choose one

Two sum done in one pass with a dict: what are the time and the extra space?

Exercise 1

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.

It should print
(0, 1)
(1, 2)
(0, 1)
None
exercise1.py
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))
Output
Press Run or Ctrl+Enter

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:

Readcounts
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}
Counting "the cat the hat the": each word read adds 1 to its count, starting from 0 the first time it is seen

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.

main.py
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])
Output
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).

main.py
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()))
Output
True False
True
[('a', 2), ('b', 1)]
Guess the outputA wrong guess is fine

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))
Choose one

Checking whether two words of length n are anagrams: Counter(a) == Counter(b) versus sorted(a) == sorted(b). What does each cost?

Exercise 2

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.

It should print
[('d', 4), ('a', 3)]
[('x', 2), ('y', 2)]
[('x', 2), ('y', 2), ('z', 1)]
exercise2.py
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))
Output
Press Run or Ctrl+Enter

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:

"".join(sorted(w))aetantabt

Grouping by sorted letters: words with the same key go into the same bucket, and each bucket is a group
main.py
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()))
Output
[['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).

PatternWhat the dict holdsTypical problemsTime
Remember what you've seenvalue → index (or a set of values)two-sum, any duplicates, longest substring without repeatsO(n)
Countingthing → count (Counter)top k most common, anagrams, first unique characterO(n)
Grouping by a keyworked-out key → listgrouping anagrams, sorting things into kindsO(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".

Choose one

Grouping anagrams: which of these can be the key in groups[...]?

Exercise 3

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.

It should print
[['ate', 'eat', 'tea'], ['bat'], ['nat', 'tan']]
[['a']]
[]
exercise3.py
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([]))
Output
Press Run or Ctrl+Enter

How you write it at work

All three patterns have ready-made tools:

main.py
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))
Output
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: sorted first.
Guess the outputA wrong guess is fine

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))

Summary

Take-away

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.

Guess the outputA wrong guess is fine

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))
Guess the outputA wrong guess is fine

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)
Guess the outputA wrong guess is fine

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)
Guess the outputA wrong guess is fine

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)
Guess the outputA wrong guess is fine

Count the letters of mississippi. What does it print?

1from collections import Counter2 3c = Counter("mississippi")4print(c.most_common(2), c["z"])