collections — Counter, defaultdict & deque
IntermediateCounter counts anything in one line, defaultdict removes key-existence boilerplate, deque gives O(1) queues — three imports that shorten half of all interview solutions.
Overview
The collections module upgrades the built-in containers. Counter is a dict specialized for frequencies with most_common() built in — anagrams, top-K, majority element all collapse into one-liners. defaultdict auto-creates missing values (list for grouping, int for counting), removing every "if key not in d" check. deque is a double-ended queue with O(1) appends and pops on BOTH ends — the correct BFS queue (list.pop(0) is O(n)). If you learn three stdlib tools for interviews, learn these.
Counter — Frequencies in One Line
Counter accepts any iterable. It supports arithmetic (subtract counts!), most_common(k), and comparing two Counters solves anagrams instantly.
from collections import Counter
votes = ["asha", "ravi", "asha", "neha", "asha", "ravi"]
c = Counter(votes)
print(c) # Counter({'asha': 3, 'ravi': 2, 'neha': 1})
print(c.most_common(2)) # [('asha', 3), ('ravi', 2)]
print(c["missing"]) # 0 — no KeyError!
# Anagram check — one line
print(Counter("listen") == Counter("silent")) # True
# Top-K frequent elements (LeetCode 347) — two lines
nums = [1, 1, 1, 2, 2, 3]
print([n for n, _ in Counter(nums).most_common(2)]) # [1, 2]
# Counter arithmetic — "can I build this word from these letters?"
letters = Counter("aabbcc")
word = Counter("abc")
print(not (word - letters)) # True — nothing missingdefaultdict & deque
defaultdict(list) makes grouping one line per item; defaultdict(int) is a counter you can increment blindly. deque is the BFS/sliding-window workhorse: popleft() is O(1).
from collections import defaultdict, deque
# Group anagrams (LeetCode 49) — THE defaultdict showcase
words = ["eat", "tea", "tan", "ate", "nat"]
groups = defaultdict(list)
for w in words:
groups["".join(sorted(w))].append(w) # no key check needed!
print(list(groups.values()))
# [['eat', 'tea', 'ate'], ['tan', 'nat']]
# Graph adjacency list
edges = [(1, 2), (1, 3), (2, 4)]
graph = defaultdict(list)
for u, v in edges:
graph[u].append(v)
# BFS with deque — O(1) queue operations
def bfs(start):
q = deque([start])
seen = {start}
while q:
node = q.popleft() # list.pop(0) would be O(n)!
for nb in graph[node]:
if nb not in seen:
seen.add(nb)
q.append(nb)
return seen
print(bfs(1)) # {1, 2, 3, 4}
# deque also: appendleft(), maxlen= for sliding windowsKey Points to Remember
- 1Counter: most_common(k), zero for missing keys, arithmetic between counters
- 2defaultdict(list) for grouping, defaultdict(int) for counting — no key checks
- 3deque: O(1) append/pop on both ends — always use it for BFS queues
- 4Counter(a) == Counter(b) is the cleanest anagram test
Interview Questions
Sign in to ask AriaGroup a list of words into anagram groups — which collections tool and why?
Why is deque required for BFS instead of a list?
Find the k most frequent elements in an array in two lines.
Ask Aria about collections — Counter, defaultdict & deque
Your personal AI tutor — ask anything about this concept
Revision Status
Personal Notes
Sign in to save personal notes for this topic.
Discussion
Sign in to join the discussion.