Counting, grouping and seen-before: three hash map patterns
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.
| Pattern | Question it answers | Key | Value |
|---|---|---|---|
| Counting | How many of each? | the item | a count |
| Grouping | Which ones belong together? | what the members share | a list of members |
| Seen-before | Have I met this, or its partner? | the item | nothing: 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.
- 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.
- 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.
- reading now
- just added
- the pair
Is there a pair that adds up to 10? The set of values seen so far is empty.
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.
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.
| The problem says | Pattern | Example |
|---|---|---|
| most frequent, how many, same letters, at least k times | Counting | Valid Anagram, Top K Frequent Elements |
| group, bucket, which ones share, classify | Grouping | Group Anagrams |
| duplicate, already, pair, complement, is there a | Seen-before | Contains Duplicate, Two Sum |
| longest run, next value, starts a sequence | Seen-before on a full set | Longest 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
09 Practise this
x − 1 is there to find where each run starts.Solve it →