Why This Matters
Frequency logic appears everywhere: anagram checks, duplicate detection, majority elements, histogram comparisons, and top-k counts. collections.Counter gives that pattern a direct Python shape.
Core Idea
collections.Counter is a dictionary subclass for counting hashable items.
| Task | Counter move |
|---|---|
| Count values | Counter(values) |
| Add more observations | update(iterable) |
| Remove observations | subtract(iterable) |
| Get top frequencies | most_common(k) |
| Compare multisets | compare Counter objects |
Non-Example or Failure Mode
Counter.subtract can leave zero or negative counts. That is useful for audits, but it can break logic that assumes all counts are positive.
Runnable Drill
Counter patterns drill
Output will appear here.
Common Mistakes
| Mistake | Correction |
|---|---|
| Rewriting manual frequency maps every time. | Use Counter when the problem is plainly about counts. |
Assuming most_common tie order is the problem's desired tie-break. | Add an explicit sort or heap key if ties matter. |
Forgetting zero and negative counts after subtract. | Clean or inspect the counter before using it as a positive multiset. |
| Using Counter when order matters. | Counter stores counts, not sequence order. |
Diagnostic Questions
| Question type | Question | Answer signal |
|---|---|---|
| Definition | What does collections.Counter store? | A map from item to frequency count. |
| Example / non-example | Is an anagram check a Counter pattern? | Yes, compare character counts. |
| Computation | What does most_common(1) return? | A list containing the highest-frequency (item, count) pair. |
| Transfer | How can Counter feed top-k? | Count first, then use most_common or heapq. |
Exercises
Beginner:
- Count characters in a string.
- Check whether two strings are anagrams.
- Find the most common item in a list.
Intermediate:
- Detect whether one multiset covers another.
- Use
Counterwithheapqto implement custom top-k tie-breaking.
Challenge:
- Implement minimum-window substring using a target
Counterand a moving window count.
References
- Python documentation.
collections.Counter: https://docs.python.org/3/library/collections.html#collections.Counter - Python documentation. Dictionary view objects and mapping behavior: https://docs.python.org/3/library/stdtypes.html#mapping-types-dict