Skip to content

Counting, grouping and seen-before: three hash map patterns

BasicsConcept

Hash map problems come in many costumes, but the code inside them takes one of three shapes: count things, group things, or ask whether you have seen something before. Here is each one on a small example, so you can spot them.

01 One tool, three shapes

Without a map, each of these problems hides the same slow step: for every item, search the items you already passed. Counting votes rescans earlier votes, grouping compares each word with every group, and finding a pair tries every earlier number. That is O(n²).

A hash map turns that search into one lookup, which takes about constant time on average. What you store in it decides which of the three shapes you have.

The three shapes at a glance
PatternQuestion it answersKeyValue
CountingHow many of each?the itema count
GroupingWhich ones belong together?what the members sharea list of members
Seen-beforeHave I met this, or its partner?the itemnothing: a set

02 Counting: how many of each

Read the items once. For each one, add one to its count, starting from 0 if it is new.

Count the votes
Step 1 of 7
6 votes
ana0
ben1
ana2
cy3
ben4
ana5
name → votes
Empty
  • reading now
  • just stored

Six votes to count. The map starts empty: nobody has a vote yet.

Many questions are counting in disguise. Two words are anagrams when their letter counts match. The most common item is the key with the biggest count. Top-k frequent is counting followed by picking the k biggest counts.

03 Grouping: which ones belong together

Grouping is counting that keeps the items. The value is a list, and each item is appended to the list under its key.

Group words by first letter
Step 1 of 7
6 words
ant0
bee1
ape2
cow3
bat4
cat5
first letter → words
Empty
  • reading now
  • just stored

Group six words by their first letter. No groups exist yet.

The whole skill is choosing the key: the thing every member of a group has and no outsider has. First letter groups ant with ape. Sorted letters group anagrams, because listen and silent both sort to eilnst. A (year, month) pair groups dates by month.

04 Seen-before: have I met this already

Keep a set of everything you have passed. In the plain form you ask "is x in the set?", which finds duplicates. In the stronger form you ask about a partner: for a pair adding to 10, x needs 10 − x.

Find two numbers that add up to 10
Step 1 of 6
5 numbers
40
91
22
73
64
seen so far
Empty
  • reading now
  • just added
  • the pair

Is there a pair that adds up to 10? The set of values seen so far is empty.

10 target

The order inside the loop matters: ask first, then add. Asking first means x is only compared with numbers before it, so it can never pair with itself. Longest Consecutive Sequence uses the same set a different way: put every number in first, then ask "is x − 1 there?" to find where each run starts.

05 All three in code

Each pattern is a few lines in Python. get(name, 0) gives 0 for a missing key, and setdefault makes the empty list the first time a key is seen.

patterns.py
# Counting: key = the item, value = how many times
votes = ["ana", "ben", "ana", "cy", "ben", "ana"]
counts = {}
for name in votes:
counts[name] = counts.get(name, 0) + 1
print(counts)
# Grouping: key = what the members share, value = a list of members
words = ["ant", "bee", "ape", "cow", "bat", "cat"]
groups = {}
for word in words:
groups.setdefault(word[0], []).append(word)
print(groups)
# Seen-before: a set of what you have passed, asked before you add
def has_pair(nums, target):
Text
$ python3 patterns.py
{'ana': 3, 'ben': 2, 'cy': 1}
{'a': ['ant', 'ape'], 'b': ['bee', 'bat'], 'c': ['cow', 'cat']}
(4, 6)

Python also ships shortcuts: collections.Counter(votes) does the counting loop, and defaultdict(list) does the grouping one. They are worth using once you can write the loop without them.

06 Which pattern is it?

The wording of a problem usually gives the pattern away.

What the problem says, and the shape it points to
The problem saysPatternExample
most frequent, how many, same letters, at least k timesCountingValid Anagram, Top K Frequent Elements
group, bucket, which ones share, classifyGroupingGroup Anagrams
duplicate, already, pair, complement, is there aSeen-beforeContains Duplicate, Two Sum
longest run, next value, starts a sequenceSeen-before on a full setLongest Consecutive Sequence

07 When it bites

counts[name] += 1Counting a key that is not there yetIn Python this raises KeyError on the first vote for each name. Use counts.get(name, 0) + 1, Counter or defaultdict(int).
groups[sorted(word)]A key that can changesorted returns a list, and Python refuses it as a key: TypeError: unhashable type: 'list'. A key must not change after it goes in, so use tuple(sorted(word)) or ''.join(sorted(word)).
seen.add(x) if target - x in seen:Adding before askingFor target 8, the first 4 adds itself and then finds 8 − 4 = 4: a pair of one number. Ask first, then add.
for k in java_hash_map.keySet()Trusting the orderPython dicts (3.7 and later) and JavaScript Map keep insertion order; Java’s HashMap promises no order at all. If the answer must be sorted, by count or by key, sort it yourself.

08 Check yourself

Question

To check whether two words are anagrams, what do you build for each word?

Question

In the pair search, why ask the set about target − x before adding x?

Question

You want listen, silent and enlist in one group, and listed somewhere else. Which key works?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?