Builds onHash map lookup
01The idea
Many problems care about how often things appear, not where they appear. A hash map that stores each value with its count answers those questions in one pass.
The counting loop is always the same:
counts[x] = counts.get(x, 0) + 1
get(x, 0) returns 0 for a value you have not seen, so the same line handles new and old values. Python also has collections.Counter, which does this loop for you.
Counting takes two passes. The first pass counts the whole input. The second pass reads the counts to answer the question. You need the first pass to finish before you can trust a count. A value that looks unique halfway through may show up again later.
The same idea works for grouping. Instead of a count, store a list. The key is whatever the items in a group share: the sorted letters of a word, the remainder after dividing by k, or the first letter. Every item with that key goes into the same list.
When you only need to know whether something is present, use a set. It is a hash map with keys and no values.
02How to spot it
Reach for counting or grouping when the problem:
- says "frequency", "most common", "appears exactly k times", "unique" or "duplicate"
- compares two collections where order does not matter, such as two words made of the same letters
- asks you to group items that share a property
- needs the k most frequent items, which starts with counting and then sorting or using a heap
If the keys come from a small fixed range, an array is enough. For lowercase letters, use 26 slots with ord(ch) - ord("a") as the index. It is faster than a hash map and as clear.
This is different from the hash map lookup pattern. There, you check each item against the items before it as you go. Here, you count everything first and decide afterwards.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue