Courses › Coding Interviews › Getting Started

Python for Interviews

The standard-library toolkit, sorting keys, heap tiebreakers and the traps that cause wrong answers.

Python is the most popular interview language for good reason: it's short, readable and comes with the data structures you need. But you only get those benefits if you know the standard library well enough to use it without thinking, and you know the handful of traps that cause wrong answers or slow code.

The toolkit

from collections import Counter, defaultdict, deque
from bisect import bisect_left
from functools import cache
import heapq

# Top two most frequent letters
print(Counter("mississippi").most_common(2))        # [('i', 4), ('s', 4)]

# Group anagrams
groups = defaultdict(list)
for w in ["eat", "tea", "tan", "ate", "nat"]:
    groups["".join(sorted(w))].append(w)
print(list(groups.values()))

# BFS queue
q = deque([0])
q.append(1)
print(q.popleft())                                    # 0

# Max-heap: push negated values
h = []
for x in [3, 1, 4, 1, 5]:
    heapq.heappush(h, -x)
print(-heapq.heappop(h))                              # 5

# k smallest / largest without sorting everything
print(heapq.nsmallest(2, [5, 2, 8, 1]))               # [1, 2]

# Binary search on a sorted list
print(bisect_left([1, 3, 3, 7], 3))                   # 1

# Memoized recursion
@cache
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(80))                                        # 23416728348467685

Sorting with keys

sort and sorted are stable and take a key function. Sort by several fields with a tuple, and reverse one numeric field by negating it.

people = [("ana", 31), ("bo", 25), ("cy", 31)]
# Age descending, then name ascending
print(sorted(people, key=lambda p: (-p[1], p[0])))   # [('ana', 31), ('cy', 31), ('bo', 25)]

intervals = [[5, 6], [1, 3], [2, 4]]
intervals.sort(key=lambda iv: iv[0])
print(intervals)                                      # [[1, 3], [2, 4], [5, 6]]

For an ordering that can't be written as a key (for example, "largest number" by comparing a + b with b + a), use functools.cmp_to_key. See Sorting & Quickselect.

Heaps with tuples

heapq compares tuples element by element. If two first elements tie, it compares the second ones, which crashes when they're objects that can't be compared, such as list nodes. Add a counter as a tiebreaker:

import heapq
import itertools

class Node:
    def __init__(self, val):
        self.val = val

counter = itertools.count()
heap = []
for node in [Node(2), Node(1), Node(2)]:
    heapq.heappush(heap, (node.val, next(counter), node))   # never compares two Nodes
print([heapq.heappop(heap)[0] for _ in range(3)])            # [1, 2, 2]

The traps

bad = [[0] * 3] * 2
bad[0][0] = 1
print(bad)            # [[1, 0, 0], [1, 0, 0]]  both rows changed

good = [[0] * 3 for _ in range(2)]
good[0][0] = 1
print(good)           # [[1, 0, 0], [0, 0, 0]]

Idioms that keep code short and clear

  • for i, x in enumerate(nums) instead of indexing by hand
  • for a, b in zip(xs, ys) to walk two sequences together; zip(nums, nums[1:]) for adjacent pairs
  • divmod(n, 10) returns the quotient and remainder together
  • max(items, key=len) and min(..., default=0) avoid manual loops and empty-input errors
  • a, b = b, a + b swaps or updates without a temporary variable
  • Python integers never overflow, so you don't need overflow checks unless the problem asks you to simulate 32-bit behavior

[!INTERVIEW] Use the library, but know what it costs Using Counter or heapq is expected, not cheating. But be ready to explain the cost of each call: heapq.heappush is O(log n), sorted is O(n log n), and x in some_list is O(n). If the interviewer asks you to implement a heap or binary search yourself, do it without complaint.

Should you use Python?

Use the language you're most fluent in. If that's Python, it's an excellent choice. If you're stronger in Java, C++ or Go, use that. A language you know well beats a concise one you don't. Some interviews (for example, for C++ systems or Android roles) expect a specific language, so check with your recruiter.

[!TIP] Related Big-O Cheat Sheet · Common Mistakes · Heaps & Top-K · Online Assessments