Algorithm patterns
Most algorithmic problems reduce to a small set of reusable patterns. Use the recognition table to map problem cues to the right template, then adapt the minimal Python skeleton. All runnable blocks share one session using data/houses.csv and data/reviews.csv:
from collections import defaultdict, dequeimport heapq
import numpy as npimport pandas as pd
houses = pd.read_csv("data/houses.csv")reviews = pd.read_csv("data/reviews.csv", keep_default_na=False)Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Time |
|---|---|---|
| find a pair or remove duplicates in a sorted array | two pointers (opposite or fast/slow) | |
| find the best contiguous subarray or substring | sliding window (expand right, shrink left) | |
| find the minimum feasible threshold or capacity | binary search on the answer space | |
| maintain a running top- or merge sorted streams | min-heap (heapq) |
|
| shortest path in an unweighted graph or grid | BFS (deque) |
|
| explore all paths, connected components, or cycle checks | DFS (recursive or explicit stack) | |
| shortest path with non-negative edge weights | Dijkstra (heapq + lazy stale-entry skip) |
|
| shortest path with negative weights / negative cycles | Bellman–Ford (relax edges times) | |
| order tasks with dependencies and detect cycles | Kahn’s topological sort (deque + in-degrees) |
|
| optimize over overlapping subproblems | DP (top-down @lru_cache or bottom-up table) |
|
| schedule maximum non-overlapping intervals | greedy sort by end time | |
| find the -th smallest item or median without sorting | Quickselect (randomized partition) | expected |
Pattern recognition guide
Section titled “Pattern recognition guide”| If you see… | Pattern | Key invariant / trick | Complexity |
|---|---|---|---|
| sorted array + target sum / deduplicate in place | Two pointers | move left or right monotonically |
time, space |
| “longest/shortest contiguous subarray/substring with…” | Sliding window | expand right; while invalid, shrink left |
time |
| “next greater/smaller element” or span of bars | Monotonic stack | pop elements that violate sorted order | amortized |
| “minimum capacity / speed so condition holds” (monotonic predicate) | Binary search on answer | lo infeasible, hi feasible; mid = (lo + hi) // 2 |
|
| “top ”, “streaming median”, or “merge sorted lists” | Heap (heapq) |
keep size- min-heap (or max-heap + min-heap for median) | |
| “minimum steps / hops” in unweighted graph or grid | BFS | mark visited when enqueuing, not when popping | |
| “all subsets / combinations / permutations” | Backtracking (DFS) | choose → recurse → undo choice | or |
| “shortest path” with weights | Dijkstra | skip popped (d, u) if d > dist[u] |
|
| “prerequisites”, “build order”, “pipeline DAG” | Kahn’s topo sort | push nodes with in_degree == 0; cycle if len(order) < V |
|
| “count ways”, “min cost”, “can reach”, choice at step | 1D DP | dp[i] depends on earlier states; compress to if rolling |
– |
| two sequences (align, edit distance, LCS) or item + budget | 2D DP | table dp[i][j]; can often keep only previous row |
|
| “maximum non-overlapping intervals” or “minimum coins (canonical)” | Greedy | prove exchange property; sort by end time for intervals | |
| “-th smallest / percentile” in unsorted array | Quickselect | random pivot avoids on sorted input | avg |
Array and search patterns
Section titled “Array and search patterns”Sliding window and binary search on answer
Section titled “Sliding window and binary search on answer”Use sliding window when adding an element at right and removing at left moves a condition monotonically (non-negative numbers, character counts). Use binary search on answer whenever a check feasible(x) flips once from False to True.
def longest_subarray_under_budget(costs: list[int], budget: int) -> int: """Length of the longest contiguous slice with sum <= budget.""" left = total = best = 0 for right, val in enumerate(costs): total += val while total > budget: total -= costs[left] left += 1 best = max(best, right - left + 1) return best
def min_truck_capacity(weights: list[int], days: int) -> int: """Smallest daily truck capacity to ship weights in order within `days`.""" lo, hi = max(weights), sum(weights) while lo < hi: mid = (lo + hi) // 2 used, load = 1, 0 for w in weights: if load + w > mid: used += 1 load = 0 load += w if used <= days: hi = mid else: lo = mid + 1 return lo
print("longest window:", longest_subarray_under_budget([4, 2, 1, 5, 1, 2], budget=8))print("min capacity:", min_truck_capacity([3, 2, 2, 4, 1, 4], days=3))longest window: 3min capacity: 6Graph traversals and shortest paths
Section titled “Graph traversals and shortest paths”| Algorithm | Edge weights | Finds | Data structure | Time |
|---|---|---|---|---|
| BFS | unweighted (all 1) | shortest path from source | deque |
|
| DFS | any | reachability, components, cycles, topo order | recursion / list stack |
|
| Dijkstra | non-negative () | single-source shortest paths | heapq min-heap |
|
| Bellman–Ford | any (detects negative cycles) | single-source shortest paths | edge list | |
| A* | non-negative + admissible heuristic | shortest path to one goal | heapq keyed by |
depends on |
| Kahn’s algorithm | directed graph | topological order + cycle check | deque + in_degree |
Dijkstra with path reconstruction and Kahn’s topological sort
Section titled “Dijkstra with path reconstruction and Kahn’s topological sort”def dijkstra( graph: dict[str, list[tuple[str, float]]], start: str, goal: str) -> tuple[float, list[str]]: dist: dict[str, float] = {start: 0.0} prev: dict[str, str | None] = {start: None} heap: list[tuple[float, str]] = [(0.0, start)] while heap: d, u = heapq.heappop(heap) if d > dist.get(u, float("inf")): continue if u == goal: break for v, w in graph.get(u, []): nd = d + w if nd < dist.get(v, float("inf")): dist[v] = nd prev[v] = u heapq.heappush(heap, (nd, v)) path: list[str] = [] cur: str | None = goal while cur is not None: path.append(cur) cur = prev.get(cur) return dist[goal], path[::-1]
routes = { "Chicago": [("Detroit", 283), ("Atlanta", 716), ("Denver", 1003)], "Detroit": [("New York", 614), ("Atlanta", 722)], "Atlanta": [("New York", 865), ("Houston", 793)], "Denver": [("Houston", 1031)], "New York": [], "Houston": [],}miles, best_path = dijkstra(routes, "Chicago", "New York")print(f"shortest route: {best_path} ({miles:.0f} mi)")
def topo_sort(nodes: list[str], edges: list[tuple[str, str]]) -> list[str]: """Return topological order or raise ValueError if a cycle exists.""" adj: dict[str, list[str]] = defaultdict(list) indeg = {n: 0 for n in nodes} for u, v in edges: adj[u].append(v) indeg[v] += 1 q = deque(n for n in nodes if indeg[n] == 0) order: list[str] = [] while q: u = q.popleft() order.append(u) for v in adj[u]: indeg[v] -= 1 if indeg[v] == 0: q.append(v) if len(order) != len(nodes): raise ValueError("Cycle detected in dependency graph") return order
steps = ["ingest", "validate", "clean", "features", "train", "export"]deps = [ ("ingest", "validate"), ("validate", "clean"), ("clean", "features"), ("features", "train"), ("train", "export"),]print("pipeline order:", topo_sort(steps, deps))shortest route: ['Chicago', 'Detroit', 'New York'] (897 mi)pipeline order: ['ingest', 'validate', 'clean', 'features', 'train', 'export']Dynamic programming
Section titled “Dynamic programming”Every DP solution defines four pieces before writing code:
- State: what
dp[i]ordp[i][j]means in plain words. - Transition: how
dp[i]is built from strictly smaller states. - Base cases: empty prefix, zero budget, or single element.
- Evaluation order: top-down (
@lru_cache) follows recursion naturally; bottom-up fills a table iteratively with lower overhead and easy row compression.
| Style | Pros | Cons | When to pick |
|---|---|---|---|
Top-down (@lru_cache) |
writes directly from recurrence; computes only reachable states | recursion limit (~1000 in Python); dict lookup overhead | trees, sparse state spaces, quick prototypes |
| Bottom-up (tabulation) | no recursion limit; easy to drop memory from to | must order loops carefully | 1D/2D grids, edit distance, knapsack, production loops |
Levenshtein edit distance and 0/1 knapsack
Section titled “Levenshtein edit distance and 0/1 knapsack”def edit_distance(a: str, b: str) -> int: """Minimum single-character inserts, deletes, or substitutions.""" prev = list(range(len(b) + 1)) for i, ca in enumerate(a, start=1): curr = [i] + [0] * len(b) for j, cb in enumerate(b, start=1): cost = 0 if ca == cb else 1 curr[j] = min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost) prev = curr return prev[-1]
def knapsack_01(weights: list[int], values: list[int], capacity: int) -> int: """Maximum value fitting in `capacity`, using each item at most once.""" dp = [0] * (capacity + 1) for w, v in zip(weights, values): for c in range(capacity, w - 1, -1): # iterate backward to prevent reuse dp[c] = max(dp[c], dp[c - w] + v) return dp[capacity]
vocab = ["received", "definitely", "quality", "battery", "recommend"]typos = ["recieved", "definately", "qualty", "batery"]fixes = [f"{t}->{min(vocab, key=lambda w: edit_distance(t, w))}" for t in typos]print("typo fixes:", ", ".join(fixes))typo_hits = reviews["text"].str.contains("|".join(typos), case=False).sum()print("reviews with those typos:", int(typo_hits))print("knapsack best value:", knapsack_01([2, 3, 4, 5], [3, 4, 5, 8], capacity=7))typo fixes: recieved->received, definately->definitely, qualty->quality, batery->batteryreviews with those typos: 73knapsack best value: 11Greedy and divide-and-conquer
Section titled “Greedy and divide-and-conquer”Interval scheduling and Quickselect
Section titled “Interval scheduling and Quickselect”Greedy works only when a locally optimal choice never blocks a globally optimal solution (the greedy-choice property). For non-overlapping intervals, sorting by finish time leaves the maximum room for remaining intervals; sorting by start time or shortest duration fails.
Quickselect finds the -th smallest element in expected time by partitioning around a random pivot and recursing on only one side.
def max_non_overlapping(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]: """Select the largest set of non-overlapping [start, end] intervals.""" chosen: list[tuple[int, int]] = [] last_end = -1 for start, end in sorted(intervals, key=lambda iv: iv[1]): if start >= last_end: chosen.append((start, end)) last_end = end return chosen
def quickselect(arr: list[int], k: int, rng: np.random.Generator) -> int: """Return the k-th smallest item (0-indexed) in O(n) expected time.""" nums = arr.copy() lo, hi = 0, len(nums) - 1 while lo <= hi: pivot = nums[int(rng.integers(lo, hi + 1))] lt, i, gt = lo, lo, hi # 3-way partition handles duplicate values cleanly while i <= gt: if nums[i] < pivot: nums[lt], nums[i] = nums[i], nums[lt] lt += 1 i += 1 elif nums[i] > pivot: nums[i], nums[gt] = nums[gt], nums[i] gt -= 1 else: i += 1 if k < lt: hi = lt - 1 elif k > gt: lo = gt + 1 else: return nums[k] raise RuntimeError("unreachable")
campaigns = [(1, 6), (2, 4), (4, 7), (5, 9), (7, 10)]print("greedy schedule:", max_non_overlapping(campaigns))
prices = houses["price"].tolist()rng = np.random.default_rng(42)k_med = len(prices) // 2qs_val = quickselect(prices, k_med, rng)exact_val = sorted(prices)[k_med]print(f"Quickselect price[{k_med}]: {qs_val} (matches sorted: {qs_val == exact_val})")greedy schedule: [(2, 4), (4, 7), (7, 10)]Quickselect price[1500]: 376000 (matches sorted: True)Gotchas
Section titled “Gotchas”| Trap | Symptom | Fix |
|---|---|---|
| sliding window with negative numbers | shrinking left can increase the sum, missing the optimal window |
use prefix sums + hash map or monotonic deque |
| marking BFS nodes visited on pop instead of enqueue | duplicate nodes flood the queue (exponential blow-up on grids) | add to visited immediately when appending to deque |
| running Dijkstra on negative edge weights | returns a suboptimal path without error | use Bellman–Ford when any edge weight can be negative |
forgetting if d > dist[u]: continue in Dijkstra |
stale heap entries re-relax all neighbors | skip outdated entries popped from heapq |
forward loop for c in range(w, cap + 1) in 1D 0/1 knapsack |
silently reuses the same item multiple times (unbounded knapsack) | iterate c backward from capacity down to w |
| picking a greedy sort key without a counterexample check | sorting intervals by start time or length fails on overlapping spans | sort by earliest end time for interval scheduling |
| 2-way Quickselect on arrays with many duplicates | degrades toward | use 3-way (Dutch National Flag) partition + random pivot |
| deep top-down DP recursion on | RecursionError: maximum recursion depth exceeded |
rewrite bottom-up iteratively |
binary search while lo <= hi with hi = mid |
infinite loop when lo == hi |
use while lo < hi with mid = (lo + hi) // 2 and lo = mid + 1 / hi = mid |