Skip to content

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, deque
import heapq
import numpy as np
import pandas as pd
houses = pd.read_csv("data/houses.csv")
reviews = pd.read_csv("data/reviews.csv", keep_default_na=False)
I want to… Use… Time
find a pair or remove duplicates in a sorted array two pointers (opposite or fast/slow) O(n)O(n)
find the best contiguous subarray or substring sliding window (expand right, shrink left) O(n)O(n)
find the minimum feasible threshold or capacity binary search on the answer space O(nlog⁡R)O(n \log R)
maintain a running top-kk or merge kk sorted streams min-heap (heapq) O(nlog⁡k)O(n \log k)
shortest path in an unweighted graph or grid BFS (deque) O(V+E)O(V + E)
explore all paths, connected components, or cycle checks DFS (recursive or explicit stack) O(V+E)O(V + E)
shortest path with non-negative edge weights Dijkstra (heapq + lazy stale-entry skip) O((V+E)log⁡V)O((V + E)\log V)
shortest path with negative weights / negative cycles Bellman–Ford (relax edges V−1V - 1 times) O(VE)O(VE)
order tasks with dependencies and detect cycles Kahn’s topological sort (deque + in-degrees) O(V+E)O(V + E)
optimize over overlapping subproblems DP (top-down @lru_cache or bottom-up table) O(states×transitions)O(\text{states} \times \text{transitions})
schedule maximum non-overlapping intervals greedy sort by end time O(nlog⁡n)O(n \log n)
find the kk-th smallest item or median without sorting Quickselect (randomized partition) O(n)O(n) expected
If you see… Pattern Key invariant / trick Complexity
sorted array + target sum / deduplicate in place Two pointers move left or right monotonically O(n)O(n) time, O(1)O(1) space
“longest/shortest contiguous subarray/substring with…” Sliding window expand right; while invalid, shrink left O(n)O(n) time
“next greater/smaller element” or span of bars Monotonic stack pop elements that violate sorted order O(n)O(n) amortized
“minimum capacity / speed so condition holds” (monotonic predicate) Binary search on answer lo infeasible, hi feasible; mid = (lo + hi) // 2 O(nlog⁡R)O(n \log R)
“top kk”, “streaming median”, or “merge kk sorted lists” Heap (heapq) keep size-kk min-heap (or max-heap + min-heap for median) O(nlog⁡k)O(n \log k)
“minimum steps / hops” in unweighted graph or grid BFS mark visited when enqueuing, not when popping O(V+E)O(V + E)
“all subsets / combinations / permutations” Backtracking (DFS) choose → recurse → undo choice O(2n)O(2^n) or O(n!)O(n!)
“shortest path” with weights ≥0\ge 0 Dijkstra skip popped (d, u) if d > dist[u] O((V+E)log⁡V)O((V + E)\log V)
“prerequisites”, “build order”, “pipeline DAG” Kahn’s topo sort push nodes with in_degree == 0; cycle if len(order) < V O(V+E)O(V + E)
“count ways”, “min cost”, “can reach”, choice at step ii 1D DP dp[i] depends on earlier states; compress to O(1)O(1) if rolling O(n)O(n)–O(n2)O(n^2)
two sequences (align, edit distance, LCS) or item + budget 2D DP table dp[i][j]; can often keep only previous row O(nm)O(nm)
“maximum non-overlapping intervals” or “minimum coins (canonical)” Greedy prove exchange property; sort by end time for intervals O(nlog⁡n)O(n \log n)
“kk-th smallest / percentile” in unsorted array Quickselect random pivot avoids O(n2)O(n^2) on sorted input O(n)O(n) avg

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))
Output
longest window: 3
min capacity: 6
Algorithm Edge weights Finds Data structure Time
BFS unweighted (all 1) shortest path from source deque O(V+E)O(V + E)
DFS any reachability, components, cycles, topo order recursion / list stack O(V+E)O(V + E)
Dijkstra non-negative (≥0\ge 0) single-source shortest paths heapq min-heap O((V+E)log⁡V)O((V + E)\log V)
Bellman–Ford any (detects negative cycles) single-source shortest paths edge list O(VE)O(VE)
A* non-negative + admissible heuristic hh shortest path to one goal heapq keyed by g+hg + h depends on hh
Kahn’s algorithm directed graph topological order + cycle check deque + in_degree O(V+E)O(V + E)

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))
Output
shortest route: ['Chicago', 'Detroit', 'New York'] (897 mi)
pipeline order: ['ingest', 'validate', 'clean', 'features', 'train', 'export']

Every DP solution defines four pieces before writing code:

  1. State: what dp[i] or dp[i][j] means in plain words.
  2. Transition: how dp[i] is built from strictly smaller states.
  3. Base cases: empty prefix, zero budget, or single element.
  4. 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 O(nm)O(nm) to O(m)O(m) 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))
Output
typo fixes: recieved->received, definately->definitely, qualty->quality, batery->battery
reviews with those typos: 73
knapsack best value: 11

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 kk-th smallest element in O(n)O(n) 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) // 2
qs_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})")
Output
greedy schedule: [(2, 4), (4, 7), (7, 10)]
Quickselect price[1500]: 376000 (matches sorted: True)
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 O(n2)O(n^2) use 3-way (Dutch National Flag) partition + random pivot
deep top-down DP recursion on n>1000n > 1000 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