Cheatsheet: Python for Coding Interviews

Last updated 2026-11-23

Lists and strings

Create a list of n zeros and a 2D grid (don't use [[0]*m]*n, which repeats the same row)

row = [0] * n
grid = [[0] * m for _ in range(n)]

Slicing, reverse and copy

a[i:j]      # items i..j-1
a[::-1]     # reversed copy
b = a[:]    # shallow copy

Enumerate and zip

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

Build strings with join (s += c in a loop can be O(n²))

"".join(chars)
",".join(map(str, nums))

Character helpers

c.isalnum(); c.isdigit(); c.lower()
ord("a")      # 97
chr(97)       # 'a'
ord(c) - ord("a")  # index 0..25

Prefix sums with itertools.accumulate

from itertools import accumulate
prefix = [0, *accumulate(nums)]
# sum(nums[i:j]) == prefix[j] - prefix[i]

Dicts, sets and Counter

Count with a dict or Counter

from collections import Counter
count = Counter("banana")   # {'a': 3, 'n': 2, 'b': 1}
count.most_common(2)          # [('a', 3), ('n', 2)]

Default values with defaultdict

from collections import defaultdict
graph = defaultdict(list)
for u, v in edges:
    graph[u].append(v)
    graph[v].append(u)

get with a default

seen.get(key, 0) + 1

Group anagrams: tuples can be dict keys, lists can't

groups = defaultdict(list)
for w in words:
    groups[tuple(sorted(w))].append(w)

Set operations

a | b   # union
a & b   # intersection
a - b   # difference
x in s  # O(1) average

deque, heapq and bisect

Queue / stack with deque (O(1) at both ends)

from collections import deque
q = deque([start])
q.append(x); q.popleft()
q.appendleft(x); q.pop()

Min-heap

import heapq
h = []
heapq.heappush(h, (dist, node))
dist, node = heapq.heappop(h)
heapq.heapify(nums)   # O(n), in place
h[0]                  # smallest, no pop

Max-heap: negate

heapq.heappush(h, -x)
largest = -heapq.heappop(h)

Kth largest: keep a min-heap of size k

h = []
for x in nums:
    heapq.heappush(h, x)
    if len(h) > k:
        heapq.heappop(h)
return h[0]

Top-k shortcuts

heapq.nlargest(k, nums)
heapq.nsmallest(k, points, key=lambda p: p[0]**2 + p[1]**2)

Binary search on a sorted list

from bisect import bisect_left, bisect_right, insort
bisect_left(a, x)   # first index with a[i] >= x
bisect_right(a, x)  # first index with a[i] > x
insort(a, x)        # insert, keeping a sorted (O(n))

Sorting

sorted returns a new list; list.sort sorts in place. Both are stable, O(n log n)

nums.sort()
b = sorted(nums, reverse=True)

Sort by a key, or by several keys

intervals.sort(key=lambda x: x[0])
# count descending, then word ascending
words.sort(key=lambda w: (-count[w], w))

Custom comparator (e.g. Largest Number)

from functools import cmp_to_key
nums.sort(key=cmp_to_key(lambda a, b: -1 if a + b > b + a else 1))

Numbers and built-ins

Infinity, integer division and modulo

float("inf"), float("-inf")
7 // 2   # 3
-7 // 2  # -4 (rounds toward -inf)
int(-7 / 2)  # -3 (truncates toward 0)
divmod(7, 2) # (3, 1)

Ints never overflow; bit tricks

x & 1        # odd?
x & (x - 1)  # clear lowest set bit
bin(x).count("1")  # popcount
x.bit_count()     # popcount, Python 3.10+

Memoize a recursive function

from functools import cache

@cache
def dp(i, j):
    ...

Raise the recursion limit for deep DFS

import sys
sys.setrecursionlimit(10**6)

Templates

Binary search (first index where ok(i) is true)

lo, hi = 0, len(a)
while lo < hi:
    mid = (lo + hi) // 2
    if ok(mid):
        hi = mid
    else:
        lo = mid + 1
return lo

Sliding window (longest valid window)

left = best = 0
for right, x in enumerate(s):
    add(x)
    while not valid():
        remove(s[left])
        left += 1
    best = max(best, right - left + 1)

BFS on a grid

q = deque([(r0, c0)])
seen = {(r0, c0)}
while q:
    r, c = q.popleft()
    for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
        nr, nc = r + dr, c + dc
        if 0 <= nr < R and 0 <= nc < C and (nr, nc) not in seen and grid[nr][nc] == 1:
            seen.add((nr, nc))
            q.append((nr, nc))

DFS on a graph (iterative)

stack, seen = [start], {start}
while stack:
    node = stack.pop()
    for nxt in graph[node]:
        if nxt not in seen:
            seen.add(nxt)
            stack.append(nxt)

Backtracking (subsets)

res, path = [], []
def backtrack(i):
    if i == len(nums):
        res.append(path[:])
        return
    path.append(nums[i]); backtrack(i + 1)
    path.pop();           backtrack(i + 1)
backtrack(0)

Monotonic stack (next greater element)

res = [-1] * len(nums)
stack = []  # indices
for i, x in enumerate(nums):
    while stack and nums[stack[-1]] < x:
        res[stack.pop()] = x
    stack.append(i)

Union-Find

parent = list(range(n))
def find(x):
    while parent[x] != x:
        parent[x] = parent[parent[x]]
        x = parent[x]
    return x
def union(a, b):
    ra, rb = find(a), find(b)
    if ra == rb:
        return False
    parent[ra] = rb
    return True

Dijkstra

dist = {src: 0}
h = [(0, src)]
while h:
    d, u = heapq.heappop(h)
    if d > dist.get(u, float("inf")):
        continue
    for v, w in graph[u]:
        nd = d + w
        if nd < dist.get(v, float("inf")):
            dist[v] = nd
            heapq.heappush(h, (nd, v))

FAQ