CS concepts

Python Built-ins for Coding Interviews Explained: 7 to Memorize

Updated Dec 1, 2026 · 3 min read

Seven tools cover most Python interview code: collections.Counter for counting, defaultdict(list) for grouping, heapq for a min-heap, collections.deque for O(1) work at both ends, bisect.bisect_left for binary search on a sorted list, functools.cache for one-line memoization, and enumerate and zip for clean loops. Each one replaces a loop you would otherwise write by hand.

Python Built-ins Cheat Sheet reel cover

Key points

  • ●Counter(s) == Counter(t) checks an anagram in one line.
  • ●defaultdict(list) groups items without any 'if key not in' checks.
  • ●heapq push and pop are O(log n); heapq.nlargest handles Top K.
  • ●deque pops from both ends in O(1); list.pop(0) is O(n).
  • ●@cache on a recursive function turns exponential recursion into memoized DP.
Step-by-step visual sheet: Python Built-ins Cheat Sheet
The full visual sheet, made with Edithly.Open the interactive sheet

Why these 7 matter

Interview problems are timed, and every hand-written helper is a place to slip. Python already ships the counting, grouping, heap, queue, binary search and memo tools you keep rewriting. The visual sheet above lists them with their costs. Here's each one with the problem it cracks.

1. Counter and 2. defaultdict(list)

collections.Counter counts anything iterable. Counter("banana") gives a: 3, n: 2, b: 1. Two strings are anagrams when their counts match, so Valid Anagram (LeetCode 242) is one comparison.

defaultdict(list) creates an empty list the first time you touch a key, so grouping needs no key checks. Group Anagrams (LeetCode 49) keys each word by its sorted letters.

from collections import Counter, defaultdict

def is_anagram(s, t):
    return Counter(s) == Counter(t)

def group_anagrams(words):
    groups = defaultdict(list)
    for w in words:
        groups["".join(sorted(w))].append(w)
    return list(groups.values())

For ["eat", "tea", "tan", "ate", "nat", "bat"] you get three groups: eat, tea, ate; tan, nat; and bat.

3. heapq

heapq keeps a min-heap on a plain list. heappush and heappop both cost O(log n), and the smallest item sits at index 0. For Top K Frequent Elements (LeetCode 347), count with Counter, then ask for the k largest by count:

import heapq
from collections import Counter

def top_k_frequent(nums, k):
    cnt = Counter(nums)
    return heapq.nlargest(k, cnt, key=cnt.get)

top_k_frequent([1, 1, 1, 2, 2, 3], 2) returns [1, 2].

4. deque, and the list.pop(0) trap

This is the one that causes timeouts. list.pop(0) removes the first item and shifts everything after it, so it's O(n). Inside a loop that becomes O(n²). collections.deque appends and pops at both ends in O(1).

Operation Cost
deque.popleft() / deque.append(x) O(1)
list.pop(0) O(n)

Use a deque as your BFS queue, and as the window of indices in Sliding Window Maximum (LeetCode 239).

from collections import deque

q = deque([start])
while q:
    node = q.popleft()

5. bisect_left

bisect.bisect_left(a, x) returns the leftmost index where x could go in a sorted list, in O(log n). It's binary search you don't have to debug. In Longest Increasing Subsequence (LeetCode 300) it finds which pile each number replaces:

from bisect import bisect_left

def length_of_lis(nums):
    tails = []
    for x in nums:
        i = bisect_left(tails, x)
        if i == len(tails):
            tails.append(x)
        else:
            tails[i] = x
    return len(tails)

For [10, 9, 2, 5, 3, 7, 101, 18] it returns 4.

6. functools.cache

Plain recursion for Climbing Stairs (LeetCode 70) repeats the same calls over and over and times out. One decorator stores each answer the first time it's computed:

from functools import cache

@cache
def climb(n):
    return 1 if n <= 1 else climb(n - 1) + climb(n - 2)

climb(5) is 8. The same trick works for Decode Ways (LeetCode 91). lru_cache(maxsize=None) does the same thing on older Python versions.

7. enumerate and zip

enumerate hands you the index and the value together, so you never write range(len(nums)). zip walks two lists side by side and stops at the shorter one.

for i, x in enumerate(nums):
    ...
for a, b in zip(xs, ys):
    ...

How to pick the right one

Start from the operation the problem needs, not the data you were given. The flowchart at the bottom of the sheet does exactly that:

  • Counting or comparing frequencies? Counter.
  • Grouping values under a key? defaultdict(list).
  • Always need the smallest, or the top k? heapq.
  • Adding and removing at both ends, or a BFS queue? deque.
  • Finding where a value goes in a sorted list? bisect_left.
  • The same recursive call keeps coming back? functools.cache.
  • Need the index, or two lists in step? enumerate or zip.

If you can name the operation out loud, you've usually picked the tool too. Interviewers like hearing that reasoning.

Bonus: membership checks

x in some_set or x in some_dict is O(1) on average. x in some_list scans every item, O(n). If you check membership inside a loop, build a set once first. The table on the visual sheet lists every cost from this page in one place.

Frequently asked questions

Why use collections.deque instead of a list for a queue in Python?

list.pop(0) shifts every remaining item one place left, so it's O(n). A deque appends and pops at either end in O(1), which is what a BFS queue needs.

What is the time complexity of heapq in Python?

heapq.heappush and heapq.heappop are O(log n). heapq keeps a min-heap on a plain list, so the smallest item is always at index 0.

What is the difference between functools.cache and lru_cache?

functools.cache is an unbounded cache, the same as lru_cache(maxsize=None). lru_cache with a size limit drops the least recently used results once it's full. For interview recursion, either works as a one-line memo.

Is x in set faster than x in list in Python?

Yes. A set or dict lookup is O(1) on average, while x in list scans the list and is O(n).

Turn any problem or document into a visual sheet like this one

Paste a LeetCode problem, a PDF or a link into Edithly and get a step-by-step sheet you can study, share or quiz yourself on.

Make this sheet in Edithly, free