Python Collections Module Interview Tips: Counter, deque, defaultdict, and More

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:

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:

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

NeedUse
Count itemsCounter
Group or build adjacency listsdefaultdict(list)
Queue for BFS, sliding windowdeque
LRU cacheOrderedDict
Top-k, scheduling, Dijkstraheapq
Readable recordsnamedtuple / dataclass

How to use these in the room

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.