Logic Building Bootcamp · Lesson 1 of 5

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.

By Shahriyar · Updated

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:

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.

▸ try it
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)   # True

Read 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

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

  1. Pattern 1 — Counting how often things appear
  2. Pattern 2 — Two Pointers
  3. Pattern 3 — Sliding Window
  4. Pattern 4 — Index Math & Matrix Walks
  5. OOP Essentials — Classes, Inheritance, Magic Methods, Decorators