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)
Slicing, reverse and copy
Enumerate and zip
Build strings with join (s += c in a loop can be O(n²))
Character helpers
Prefix sums with itertools.accumulate
Dicts, sets and Counter
Count with a dict or Counter
Default values with defaultdict
get with a default
Group anagrams: tuples can be dict keys, lists can't
Set operations
deque, heapq and bisect
Queue / stack with deque (O(1) at both ends)
Min-heap
Max-heap: negate
Kth largest: keep a min-heap of size k
Top-k shortcuts
Binary search on a sorted list
Sorting
sorted returns a new list; list.sort sorts in place. Both are stable, O(n log n)
Sort by a key, or by several keys
Custom comparator (e.g. Largest Number)
Numbers and built-ins
Infinity, integer division and modulo
Ints never overflow; bit tricks
Memoize a recursive function
Raise the recursion limit for deep DFS
Templates
Binary search (first index where ok(i) is true)
Sliding window (longest valid window)
BFS on a grid
DFS on a graph (iterative)
Backtracking (subsets)
Monotonic stack (next greater element)
Union-Find
Dijkstra