Pattern 1 — Counting how often things appear
This is the very first pattern you'll meet — and you'll use it all the time. The good news? It's just counting. Nothing scary here.
The idea, in one line
Count how many times each thing shows up. Then answer the question by looking at your counts. That's the whole pattern. It has a proper name that interviewers use — frequency counting — so it's worth remembering.
When will you need it?
Any time a question is about how often something happens. These words are your signal:
- anagram — same letters, just rearranged
- duplicate — something that shows up more than once
- most common — the thing that appears the most
- first unique — the first thing that appears only once
See it work
Python gives you a ready-made counter called Counter. You hand it a word or a list, and it does all the tallying for you.
from collections import Counter
# Count the letters in each word
a = Counter("listen") # l:1, i:1, s:1, t:1, e:1, n:1
b = Counter("silent") # s:1, i:1, l:1, e:1, n:1, t:1
# Same letters, same counts? Then they're anagrams.
print(a == b) # TrueRead it top to bottom: you counted the letters in each word, then checked whether the two counts matched. That's all an anagram check is.
The same trick answers three questions
- Anagram? — the two counts are equal
- Duplicate? — any item with a count above 1
- First unique? — the first item with a count of exactly 1
Advanced — why counting is the fast way
You might be tempted to compare every item with every other item. That works, but it's slow. Counting looks at each item just once, which is far quicker.
Grounded in the official Python docs (collections.Counter)
All lessons in Logic Building Bootcamp
- Pattern 1 — Counting how often things appear
- Pattern 2 — Two Pointers
- Pattern 3 — Sliding Window
- Pattern 4 — Index Math & Matrix Walks
- OOP Essentials — Classes, Inheritance, Magic Methods, Decorators