Python Collections Module Interview Tips: Counter, deque, defaultdict, and More
Python is a popular interview language because it lets you express ideas quickly. A big part of that speed comes from the standard library, especially the collections module and its neighbor heapq. Knowing exactly when to reach for Counter, defaultdict, or deque can save you several minutes and a few bugs in a live round.
These Python collections module interview tips cover the tools that show up most, with short examples and the trade-offs worth saying out loud.
Counter: frequency counts in one line
Counter counts hashable items.
from collections import Counter
counts = Counter("mississippi")
# Counter({'i': 4, 's': 4, 'p': 2, 'm': 1})
Where it helps: anagrams, "first unique character," majority element, top-k frequent elements.
def is_anagram(a, b):
return Counter(a) == Counter(b)
def top_k_frequent(nums, k):
return [x for x, _ in Counter(nums).most_common(k)]
Talking points:
- Building a Counter is O(n).
most_common(k)uses a heap internally when k is given, about O(n log k).- Missing keys return 0 instead of raising
KeyError, which simplifies sliding window code.
Pitfall: in a sliding window, decrementing a count to zero leaves the key in place. If you compare len(counter) to a target, delete zero entries or use a separate "distinct" counter.
defaultdict: no more "if key not in dict"
defaultdict creates a default value the first time you access a missing key.
from collections import defaultdict
graph = defaultdict(list)
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
Where it helps: adjacency lists, grouping anagrams, bucketing by key.
def group_anagrams(words):
groups = defaultdict(list)
for w in words:
groups[tuple(sorted(w))].append(w)
return list(groups.values())
Pitfall: just reading graph[x] inserts x with an empty list. If you later iterate over the dict while checking neighbors, you can get "dictionary changed size during iteration." Use graph.get(x, []) when you only want to look.
deque: fast operations at both ends
A Python list is slow at removing from the front (pop(0) is O(n)). deque does it in O(1).
from collections import deque
def bfs(start, graph):
seen = {start}
queue = deque([start])
while queue:
node = queue.popleft()
for nxt in graph[node]:
if nxt not in seen:
seen.add(nxt)
queue.append(nxt)
return seen
Where it helps: BFS, sliding window maximum (monotonic deque), recent-items buffers.
def max_sliding_window(nums, k):
dq, out = deque(), []
for i, x in enumerate(nums):
while dq and nums[dq[-1]] <= x:
dq.pop()
dq.append(i)
if dq[0] <= i - k:
dq.popleft()
if i >= k - 1:
out.append(nums[dq[0]])
return out
Talking point: deque(maxlen=n) automatically drops old items, handy for "last n events" designs.
Pitfall: indexing into the middle of a deque is O(n). Use it for ends, not random access.
OrderedDict: LRU cache in a few lines
Regular dicts keep insertion order since Python 3.7, but OrderedDict adds move_to_end and popitem(last=False), which make an LRU cache easy.
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.cap = capacity
self.data = OrderedDict()
def get(self, key):
if key not in self.data:
return -1
self.data.move_to_end(key)
return self.data[key]
def put(self, key, value):
self.data[key] = value
self.data.move_to_end(key)
if len(self.data) > self.cap:
self.data.popitem(last=False)
Talking point: some interviewers want you to build the doubly linked list yourself. Offer the OrderedDict version, then ask: "Would you like me to implement the underlying linked list instead?"
heapq: priority queues (not in collections, but always nearby)
heapq gives you a min-heap on a plain list.
import heapq
def k_smallest(nums, k):
return heapq.nsmallest(k, nums)
def kth_largest(nums, k):
heap = []
for x in nums:
heapq.heappush(heap, x)
if len(heap) > k:
heapq.heappop(heap)
return heap[0]
Talking points:
- Push and pop are O(log n);
heapifyis O(n). - For a max-heap, push negated values.
- For tuples, ties compare the next element. Add a counter as a tiebreaker if the payload isn't comparable:
(priority, count, item).
namedtuple and dataclass: readable records
When a problem has records with several fields, readability matters.
from collections import namedtuple
Interval = namedtuple("Interval", ["start", "end"])
A @dataclass works too and is easier to extend. Either one makes your code easier for the interviewer to follow than bare tuples like x[0] and x[1].
Quick chooser
| Need | Use |
|---|---|
| Count items | Counter |
| Group or build adjacency lists | defaultdict(list) |
| Queue for BFS, sliding window | deque |
| LRU cache | OrderedDict |
| Top-k, scheduling, Dijkstra | heapq |
| Readable records | namedtuple / dataclass |
How to use these in the room
- Ask if the standard library is fine. Most interviewers say yes, but asking shows awareness.
- Know the cost. Saying "deque popleft is O(1), unlike list.pop(0)" turns a library call into evidence of understanding.
- Be ready to implement from scratch if asked, especially heaps and LRU caches.
- Don't hide the logic. A clever one-liner with
Counteris great, but explain what it does.
Practice until it's automatic
The goal is to reach for the right tool without hesitation, then explain it calmly. Luna Interview helps you practice out-loud problem solving under time pressure, so these choices feel natural in the real round.
Write each example above from memory a few times this week, and you'll save real minutes when it counts.
Rehearse with an AI interview copilot, then browse commonly reported interview questions.