Count things with a dictionary
Four ways to write the same loop — get, setdefault, defaultdict and Counter — all O(n). For the k most common, do not sort everything: a heap of size k gives O(n log k), which matters when n is huge and k is ten.
Overview
The four idioms
counts[x] = counts.get(x, 0) + 1 needs no import and makes the default explicit. counts.setdefault(x, 0) is the same idea and reads worse for counting. defaultdict(int) lets you write counts[x] += 1 directly. Counter(seq) does the whole loop in C.
They are all O(n). Reach for Counter in real code and be able to write the get version when an interviewer asks you not to import anything.
Step through it
What to watch
- Each item costs one lookup and one write, whatever the dictionary holds.
- The counter grows only with distinct items.
- Nothing is ever searched for.
Say this out loud
"Counter for the counting. For top-k I'd use heapq.nlargest rather than sorting - O(n log k) instead of O(n log n), which is the difference that matters when n is a billion."