Skip to main content
TRACK B · CODING & ALGORITHMS

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).

Review the cue & invariant for each building block, or open its matching Pattern Triage prompts to see how concrete problems map to it.
TEMPLATE 01O(n) time · O(k) space

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)
#1 Common Bug: Resetting left = right on violation (breaks inputs like 'dvdf') instead of advancing left one step at a time.
Interactive Trace Sim
TEMPLATE 02O(log n) or O(n log M) time · O(1) space

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 lo
#1 Common Bug: Using while lo < hi with hi = mid - 1 (misses 1-element range) or lo = mid (infinite loop on 2 elements).
Interactive Trace Sim
TEMPLATE 03O(n) time (after sort) · O(1) space

Two 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 -= 1
#1 Common Bug: Forgetting to skip duplicate values in 3Sum or advancing the taller wall instead of the shorter one.
Interactive Trace Sim
TEMPLATE 04O(n) time · O(n) space

Hash 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) + 1
#1 Common Bug: Forgetting counts = {0: 1} before the loop (misses subarrays starting at index 0) or attempting sliding window with negatives.
Interactive Trace Sim
TEMPLATE 05O(n) time · O(n) space

Monotonic 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)
#1 Common Bug: Pushing values instead of indices (loses distance/width math) or forgetting to flush remaining stack bars at the end.
Interactive Trace Sim
TEMPLATE 06O(n log k) time · O(k) space

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 h
#1 Common Bug: Pushing all n items into a heap O(n log n) instead of capping size at K, or forgetting tie-breaker indices in Python tuples.
Interactive Trace Sim
TEMPLATE 07O(V + E) time · O(V) space

BFS 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))
#1 Common Bug: Marking visited on pop instead of on enqueue — causes exponential duplicate pushes into the queue.
Interactive Trace Sim
TEMPLATE 08O((V + E) log V) time · O(V) space

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))
#1 Common Bug: Using plain BFS on weighted edges (ignores edge cost) or skipping the stale-entry check `if d > best[u]: continue`.
Interactive Trace Sim
TEMPLATE 09O(V + E) time · O(V + E) space

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 []
#1 Common Bug: Forgetting `len(order) == n` at the end to detect a cycle, or using Union-Find on a directed DAG.
Interactive Trace Sim
TEMPLATE 10O(α(n)) ≈ O(1) amortized per op

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 False
#1 Common Bug: Comparing x == y instead of find(x) == find(y), or forgetting path compression.
Interactive Trace Sim
TEMPLATE 11O(n log n) time · O(n) space

Sort & 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])
#1 Common Bug: Writing out[-1][1] = e instead of max(out[-1][1], e) — breaks when one interval fully encloses the next.
Interactive Trace Sim
TEMPLATE 12O(L) per insert/query · O(total chars) space

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 True
#1 Common Bug: Forgetting an explicit `is_end` marker on nodes (confusing a prefix with a complete inserted word).
Interactive Trace Sim
TEMPLATE 13O(1) get & put · O(cap) space

Hash 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)
#1 Common Bug: Using a singly linked list (cannot unlink an arbitrary middle node in O(1)) or forgetting to delete the evicted key from the hash map.
Interactive Trace Sim
TEMPLATE 14O(n) time · O(1) space

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 True
#1 Common Bug: Applying greedy when subproblems conflict (e.g., arbitrary coin denominations — test a tiny counterexample first!).
Interactive Trace Sim
TEMPLATE 15O(branching^n) time · O(n) stack

Backtracking 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)
#1 Common Bug: Appending `path` instead of `path.copy()` — every saved entry turns empty by the end of DFS.
Interactive Trace Sim
TEMPLATE 16O(states × transitions)

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)
#1 Common Bug: Wrong loop direction in 0/1 knapsack (forward reuses items infinitely; backward uses each item once) or missing base case dp[0].
Interactive Trace Sim
TEMPLATE 17O(N) time · O(H) recursion stack

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)
#1 Common Bug: Returning node.val + L + R to the parent (a simple path cannot fork at a child and continue upward) or initializing best = 0 on negative trees.
Interactive Trace Sim
TEMPLATE 18O(n) time · O(k) space

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]])
#1 Common Bug: Storing values instead of indices in dq (loses the ability to evict expired indices when dq[0] <= i - k).
Interactive Trace Sim
TEMPLATE 19O(log n) insert · O(1) median

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))
#1 Common Bug: Inserting directly into lo or hi without routing lo -> hi and rebalancing sizes (breaks ordering or size invariant).
Interactive Trace Sim
TEMPLATE 20O(n × m) time · O(n × m) space

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])
#1 Common Bug: Using A[i] instead of A[i - 1] when i, j represent prefix lengths 1..n (off-by-one IndexError).
Interactive Trace Sim