Coding Patterns
Reusable Python templates (20) with step-by-step traces, pattern triage breakdowns (48) with problem-to-code mappings, and buggy code traces (3).
Variable Sliding Window
Spot it: Contiguous subarray/substring + longest/shortest/count + incrementally maintainable validity (monotonic when shrinking).
INVARIANT: Window [left, right] is valid once the inner while-loop exits; both pointers only move forward.
seen, left, best = {}, 0, 0
for right, ch in enumerate(s):
seen[ch] = seen.get(ch, 0) + 1
while invalid(seen): # shrink only until valid
seen[s[left]] -= 1
left += 1
best = max(best, right - left + 1)Binary Search (Value or Answer Space)
Spot it: Sorted/rotated array OR 'minimum capacity / maximum speed such that feasible(x)' monotonic predicate.
INVARIANT: The answer always remains inside [lo, hi]; every probe discards half the remaining space.
lo, hi = min_val, max_val
while lo < hi: # boundary template
mid = lo + (hi - lo) // 2
if feasible(mid):
hi = mid # mid works; try smaller
else:
lo = mid + 1 # mid fails; must go larger
return loTwo Pointers (Converging / Fast-Slow)
Spot it: Sorted pair/triplet sum, container area, palindrome check, or in-place deduplication / linked-list cycle.
INVARIANT: Every pointer move provably eliminates an entire row or column of inferior pairs.
l, r = 0, len(a) - 1
while l < r:
cur = a[l] + a[r]
if cur == target: return (l, r)
if cur < target: l += 1
else: r -= 1Hash Map + Prefix Sum
Spot it: Exact subarray sum == k (especially with NEGATIVE numbers!) or equal counts of two opposing states.
INVARIANT: prefix[r] - prefix[l] == k <=> prefix[l] == prefix[r] - k. Map stores all earlier prefix sums.
counts, prefix, ans = {0: 1}, 0, 0
for x in nums:
prefix += x
ans += counts.get(prefix - k, 0)
counts[prefix] = counts.get(prefix, 0) + 1Monotonic Stack
Spot it: 'Next greater/smaller element', waiting days, span to previous boundary, or largest rectangle in histogram.
INVARIANT: Stack holds indices whose values stay strictly monotonic; each index is pushed once and popped at most once.
stack, ans = [], [0] * len(nums)
for i, v in enumerate(nums):
while stack and nums[stack[-1]] < v:
prev = stack.pop()
ans[prev] = i - prev
stack.append(i)Min/Max Heap (Top-K / K-Way Merge)
Spot it: 'K largest/closest/most frequent' on a stream, merging K sorted lists, or earliest-ending scheduling.
INVARIANT: A min-heap capped at size K always holds the K largest items seen so far; heap[0] is the cutoff.
import heapq
h = []
for x in stream:
heapq.heappush(h, x)
if len(h) > k:
heapq.heappop(h) # evict smallest; K largest remain
return hBFS Shortest Path / Multi-Source Grid
Spot it: Minimum steps / shortest path in an UNWEIGHTED graph or 2D grid, or simultaneous spread from multiple sources.
INVARIANT: Queue holds nodes in non-decreasing distance order; first visit is guaranteed shortest.
from collections import deque
q, seen = deque([(start, 0)]), {start}
while q:
node, dist = q.popleft()
if node == goal: return dist
for nxt in neighbors(node):
if nxt not in seen:
seen.add(nxt) # mark on enqueue!
q.append((nxt, dist + 1))Dijkstra's Shortest Path (Weighted Graph)
Spot it: Minimum latency, cost, or effort across a graph with NON-NEGATIVE edge weights.
INVARIANT: When a node is popped from the min-heap with distance d == best[node], d is its final optimal cost.
import heapq
best = {start: 0}
pq = [(0, start)]
while pq:
d, u = heapq.heappop(pq)
if d > best.get(u, float("inf")): continue
for v, w in adj[u]:
if d + w < best.get(v, float("inf")):
best[v] = d + w
heapq.heappush(pq, (d + w, v))Topological Sort (Kahn's Algorithm)
Spot it: Prerequisites, build/pipeline DAG order, course schedule, or cycle detection in a DIRECTED graph.
INVARIANT: Queue holds only nodes with remaining indegree == 0 (all prerequisites finished).
q = deque(u for u in range(n) if indeg[u] == 0)
order = []
while q:
u = q.popleft(); order.append(u)
for v in adj[u]:
indeg[v] -= 1
if indeg[v] == 0: q.append(v)
return order if len(order) == n else []Union-Find (Disjoint Set Union)
Spot it: Dynamic undirected connectivity, merging equivalence groups (emails/accounts), or counting components as edges arrive.
INVARIANT: find(x) returns the canonical root of x's component; two items are connected iff find(a) == find(b).
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: parent[ra] = rb; return True
return FalseSort & Sweep Intervals
Spot it: Overlapping schedules, merging ranges, or peak concurrent jobs/meeting rooms.
INVARIANT: Sorting by start time means overlap with the active range depends only on out[-1][1] (or earliest end in a min-heap).
intervals.sort(key=lambda iv: iv[0])
out = [intervals[0]]
for s, e in intervals[1:]:
if s <= out[-1][1]:
out[-1][1] = max(out[-1][1], e)
else:
out.append([s, e])Trie (Prefix Tree)
Spot it: Autocomplete, shared prefix lookup, wildcard dictionary search, or routing/IP prefix matching.
INVARIANT: Every path from root of length k represents a prefix of length k in O(L) time independent of dictionary size N.
root = {}
def insert(word):
cur = root
for ch in word:
cur = cur.setdefault(ch, {})
cur["$"] = True
def starts_with(prefix):
cur = root
for ch in prefix:
if ch not in cur: return False
cur = cur[ch]
return TrueHash Map + Doubly Linked List (O(1) Cache)
Spot it: O(1) lookup + O(1) recency promotion + O(1) oldest eviction (LRU cache, TTL eviction, KV slab).
INVARIANT: Hash map gives O(1) pointer to a node; doubly linked list keeps most-recent at head and eviction victim at tail.
from collections import OrderedDict
class LRUCache:
def __init__(self, cap): self.cap, self.od = cap, OrderedDict()
def get(self, k):
if k not in self.od: return -1
self.od.move_to_end(k); return self.od[k]
def put(self, k, v):
self.od[k] = v; self.od.move_to_end(k)
if len(self.od) > self.cap: self.od.popitem(last=False)Greedy Choice / Running Reach Scan
Spot it: Local optimal decision provably never hurts future options: jump reachability, gas station circuit, or activity selection.
INVARIANT: Track one running frontier (e.g. farthest reachable index); if i ever passes frontier, the goal is unreachable.
farthest = 0
for i, step in enumerate(nums):
if i > farthest: return False
farthest = max(farthest, i + step)
return TrueBacktracking Decision Tree
Spot it: 'Return ALL subsets / permutations / valid combinations / board placements' with tiny N (N ≤ 20).
INVARIANT: path holds the current partial choice; every append before recursing is undone by pop right after.
res, path = [], []
def dfs(i):
if i == len(nums):
res.append(path.copy()); return
path.append(nums[i]); dfs(i + 1)
path.pop(); dfs(i + 1)1D / 2D Dynamic Programming
Spot it: 'Minimum cost / number of ways / max score' with overlapping subproblems where greedy fails.
INVARIANT: dp[state] stores the optimal value for that exact subproblem, computed from strictly smaller solved states.
dp = [float("inf")] * (target + 1)
dp[0] = 0
for t in range(1, target + 1):
for item in items:
if t >= item:
dp[t] = min(dp[t], dp[t - item] + 1)Binary Tree Post-Order DFS (Return vs. Split)
Spot it: Binary tree path sum, diameter, height balance, or LCA where children report a single branch upward while updating a global split.
INVARIANT: dfs(node) returns the best single-branch downward gain; global best considers two-branch splits (L + node + R).
best = float("-inf")
def dfs(node):
nonlocal best
if not node: return 0
L = max(0, dfs(node.left))
R = max(0, dfs(node.right))
best = max(best, node.val + L + R)
return node.val + max(L, R)Monotonic Deque (Sliding Window Extremes)
Spot it: Sliding window maximum/minimum over k elements, bounded max-min jitter, or shortest subarray >= K with negative values.
INVARIANT: Deque holds indices in strictly monotonic value order; dq[0] is the current window extreme and expired indices <= i - k are popped from front.
from collections import deque
dq, out = deque(), []
for i, x in enumerate(nums):
if dq and dq[0] <= i - k: dq.popleft()
while dq and nums[dq[-1]] <= x: dq.pop()
dq.append(i)
if i >= k - 1: out.append(nums[dq[0]])Two Heaps (Streaming Median & Order Stats)
Spot it: Live median / percentile from a data stream, sliding window median, or dual-priority capital/project scheduling.
INVARIANT: Max-heap lo holds smaller half, min-heap hi holds larger half; max(lo) <= min(hi) and 0 <= len(lo) - len(hi) <= 1.
import heapq
lo, hi = [], [] # lo max-heap (-x), hi min-heap
def add(x):
heapq.heappush(lo, -x)
heapq.heappush(hi, -heapq.heappop(lo))
if len(hi) > len(lo):
heapq.heappush(lo, -heapq.heappop(hi))2D Sequence / Grid Dynamic Programming
Spot it: Comparing/aligning two sequences (LCS, edit distance, regex matching) or 2D grid paths indexed by prefix lengths (i, j).
INVARIANT: dp[i][j] holds the optimal answer for prefixes A[:i] and B[:j], computed from top, left, and diagonal neighbors.
dp = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, m + 1):
if A[i - 1] == B[j - 1]:
dp[i][j] = 1 + dp[i - 1][j - 1]
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])