Skip to content

45. Algorithms and data structures II — Cheat sheet

The essentials of module 45 on one page: a quick lookup table, complexity summary, copy-ready templates and common gotchas. Every runnable snippet is verified against its output.

I want to… Use… Complexity
cache hot lookups with fixed capacity LRUCache (dict + doubly linked list) or @lru_cache O(1)O(1) get / put
autocomplete strings by prefix Trie (character tree) O(L+matches)O(L + \text{matches})
maintain connected components / groups UnionFind (path compression + rank) O(α(n))≈O(1)O(\alpha(n)) \approx O(1)
find shortest path with non-negative weights Dijkstra (heapq min-heap) O((V+E)log⁡V)O((V + E)\log V)
find shortest path with negative weights Bellman–Ford (relax edges V−1V - 1 times) O(VE)O(VE)
connect all nodes at minimum total cost Kruskal’s MST (sort edges + UnionFind) O(Elog⁡E)O(E \log E)
order tasks with prerequisites and catch cycles Kahn’s topological sort (in-degree + deque) O(V+E)O(V + E)
count ways / maximize score over prefixes 1D bottom-up DP tabulation O(n)O(n)
measure string similarity / fix typos Levenshtein edit distance (2-row DP) O(mn)O(mn) time, O(min⁡(m,n))O(\min(m, n)) space
maximize value under a fixed budget (each item once) 0/1 knapsack (backward 1D DP loop) O(nB)O(nB) time, O(B)O(B) space
schedule max non-overlapping intervals Greedy: sort by finish time ascending O(nlog⁡n)O(n \log n)
find exact median or kk-th smallest without sorting Randomized Quickselect (or np.partition) O(n)O(n) expected
query nearest neighbors in low dimensions (d≤15d \le 15) scipy.spatial.KDTree on scaled features O(log⁡n)O(\log n) typical query
test set membership in ~1.2 bytes/item BloomFilter (bit array + double hashing) O(k)O(k) time, 0% FN
estimate Jaccard similarity / find near-duplicates MinHash + LSH banding O(H)O(H) per sketch
Structure / Algorithm Build Query / Update Space Key precondition / note
Doubly linked list O(n)O(n) O(1)O(1) with node ref O(n)O(n) Sentinels remove None edge cases
LRU cache O(1)O(1) O(1)O(1) O(C)O(C) Hash map + doubly linked list
Balanced BST (AVL / RB) O(nlog⁡n)O(n \log n) O(log⁡n)O(\log n) O(n)O(n) Keeps sorted order
B-tree O(nlog⁡Bn)O(n \log_B n) O(log⁡Bn)O(\log_B n) O(n)O(n) High branching factor BB for disk pages
Trie O(∑Li)O(\sum L_i) O(L)O(L) O(nodes)O(\text{nodes}) Independent of dictionary count
Union-Find O(n)O(n) O(α(n))O(\alpha(n)) O(n)O(n) Path compression + union by rank
Dijkstra — O((V+E)log⁡V)O((V + E)\log V) O(V)O(V) Non-negative edge weights only
Kruskal MST — O(Elog⁡E)O(E \log E) O(V+E)O(V + E) Undirected weighted graph
Kahn topological sort — O(V+E)O(V + E) O(V+E)O(V + E) Detects cycles when len(order) < V
Levenshtein DP — O(mn)O(mn) O(min⁡(m,n))O(\min(m, n)) Two rolling rows
0/1 Knapsack — O(nB)O(nB) O(B)O(B) Iterate capacity backward
Quickselect — O(n)O(n) expected O(1)O(1) extra Random pivot avoids O(n2)O(n^2)
KD-tree O(nlog⁡n)O(n \log n) O(log⁡n)O(\log n) low-dd O(n)O(n) Scale features; degrades for d>20d \gt 20
Bloom filter O(nk)O(nk) O(k)O(k) mm bits No deletions; 0 false negatives
MinHash O(H⋅∣S∣)O(H \cdot \lvert S \rvert) O(H)O(H) compare O(H)O(H) Unbiased estimator of Jaccard
from collections import OrderedDict
class SimpleLRU:
"""Compact O(1) LRU cache using OrderedDict (doubly linked list in C)."""
def __init__(self, cap: int) -> None:
self.cap = cap
self.data: OrderedDict[str, float] = OrderedDict()
def get(self, key: str) -> float | None:
if key not in self.data:
return None
self.data.move_to_end(key) # mark most recently used
return self.data[key]
def put(self, key: str, val: float) -> None:
if key in self.data:
self.data.move_to_end(key)
self.data[key] = val
if len(self.data) > self.cap:
self.data.popitem(last=False) # evict least recently used
cache = SimpleLRU(cap=2)
cache.put("P001", 79.99)
cache.put("P002", 249.0)
_ = cache.get("P001") # P001 becomes MRU; P002 is now LRU
cache.put("P003", 1299.0) # evicts P002
print(list(cache.data.keys()))
Output
['P001', 'P003']
def build_trie(words: list[str]) -> dict:
root: dict = {}
for w in words:
node = root
for ch in w.lower():
node = node.setdefault(ch, {})
node["$"] = w # terminal marker
return root
def prefix_matches(root: dict, prefix: str) -> list[str]:
node = root
for ch in prefix.lower():
if ch not in node:
return []
node = node[ch]
out, stack = [], [node]
while stack:
cur = stack.pop()
for k, v in cur.items():
if k == "$":
out.append(v)
else:
stack.append(v)
return sorted(out)
t = build_trie(["wireless", "waterproof", "weeknight", "wool"])
print(prefix_matches(t, "w"), prefix_matches(t, "wi"))
Output
['waterproof', 'weeknight', 'wireless', 'wool'] ['wireless']

Union-Find, Dijkstra, Kruskal and Kahn’s sort

Section titled “Union-Find, Dijkstra, Kruskal and Kahn’s sort”
import heapq
import math
from collections import defaultdict, deque
class UnionFind:
def __init__(self, items: list[str]) -> None:
self.parent = {x: x for x in items}
self.rank = {x: 0 for x in items}
def find(self, x: str) -> str:
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]]
x = self.parent[x]
return x
def union(self, a: str, b: str) -> bool:
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False
if self.rank[ra] < self.rank[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
if self.rank[ra] == self.rank[rb]:
self.rank[ra] += 1
return True
edges = [("A", "B", 4), ("A", "C", 2), ("C", "B", 1), ("B", "D", 5), ("C", "D", 8)]
adj: dict[str, list[tuple[str, int]]] = defaultdict(list)
for u, v, w in edges:
adj[u].append((v, w))
adj[v].append((u, w))
# Dijkstra from A
dist = {"A": 0.0}
pq: list[tuple[float, str]] = [(0.0, "A")]
while pq:
d, u = heapq.heappop(pq)
if d > dist[u]:
continue
for v, w in adj[u]:
if d + w < dist.get(v, math.inf):
dist[v] = d + w
heapq.heappush(pq, (d + w, v))
# Kruskal MST
uf = UnionFind(["A", "B", "C", "D"])
mst_cost = sum(w for u, v, w in sorted(edges, key=lambda e: e[2]) if uf.union(u, v))
print("Dijkstra D:", int(dist["D"]), "MST cost:", mst_cost)
Output
Dijkstra D: 8 MST cost: 8
def kahn_sort(deps: dict[str, list[str]]) -> list[str]:
"""deps[task] = list of prerequisites. Raises ValueError on cycle."""
indeg = {u: 0 for u in deps}
fwd: dict[str, list[str]] = defaultdict(list)
for u, prereqs in deps.items():
for p in prereqs:
indeg.setdefault(p, 0)
fwd[p].append(u)
indeg[u] += 1
q = deque(sorted(u for u, d in indeg.items() if d == 0))
order = []
while q:
u = q.popleft()
order.append(u)
ready = []
for v in fwd[u]:
indeg[v] -= 1
if indeg[v] == 0:
ready.append(v)
q.extend(sorted(ready))
if len(order) != len(indeg):
raise ValueError("Cycle detected")
return order
print(kahn_sort({"extract": [], "clean": ["extract"], "train": ["clean"]}))
Output
['extract', 'clean', 'train']

Dynamic programming, greedy and Quickselect

Section titled “Dynamic programming, greedy and Quickselect”
import random
def levenshtein(a: str, b: str) -> int:
if len(a) < len(b):
a, b = b, a
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):
curr[j] = min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + (ca != cb))
prev = curr
return prev[-1]
def knapsack_01(items: list[tuple[int, int]], budget: int) -> int:
dp = [0] * (budget + 1)
for cost, val in items:
for b in range(budget, cost - 1, -1): # backward!
dp[b] = max(dp[b], dp[b - cost] + val)
return dp[budget]
def max_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:
chosen: list[tuple[int, int]] = []
for start, end in sorted(intervals, key=lambda iv: iv[1]): # earliest end first
if not chosen or start >= chosen[-1][1]:
chosen.append((start, end))
return chosen
def quickselect(nums: list[int], k: int, seed: int = 42) -> int:
arr, rng = nums[:], random.Random(seed)
lo, hi = 0, len(arr) - 1
while lo < hi:
p = rng.randint(lo, hi)
arr[p], arr[hi] = arr[hi], arr[p]
pivot, store = arr[hi], lo
for i in range(lo, hi):
if arr[i] < pivot:
arr[store], arr[i] = arr[i], arr[store]
store += 1
arr[store], arr[hi] = arr[hi], arr[store]
if k == store:
return arr[store]
if k < store:
hi = store - 1
else:
lo = store + 1
return arr[lo]
print("edit:", levenshtein("qualty", "quality"))
print("knapsack:", knapsack_01([(2, 14), (3, 22), (4, 28)], 5))
print("intervals:", max_intervals([(1, 4), (2, 3), (3, 5), (5, 7)]))
print("median:", quickselect([40, 10, 50, 20, 30], 2))
Output
edit: 1
knapsack: 36
intervals: [(2, 3), (3, 5), (5, 7)]
median: 30
import hashlib
import numpy as np
from scipy.spatial import KDTree
pts = np.array([[0.0, 0.0], [1.0, 1.0], [2.0, 2.0], [5.0, 5.0]])
tree = KDTree(pts)
d, idx = tree.query([0.9, 1.1], k=2)
print("KDTree nearest indices:", idx.tolist(), "distances:", np.round(d, 3).tolist())
# Minimal Bloom filter bit-set check (m=128 bits, k=3 hashes)
m, k = 128, 3
bits = bytearray(m // 8)
def bloom_pos(text: str) -> list[int]:
dig = hashlib.sha256(text.encode()).digest()
h1 = int.from_bytes(dig[:8], "big")
h2 = int.from_bytes(dig[8:16], "big") | 1
return [(h1 + i * h2) % m for i in range(k)]
for word in ("earbuds", "laptop"):
for p in bloom_pos(word):
bits[p // 8] |= 1 << (p % 8)
def bloom_has(word: str) -> bool:
return all((bits[p // 8] >> (p % 8)) & 1 for p in bloom_pos(word))
print("Bloom checks:", bloom_has("earbuds"), bloom_has("toaster"))
Output
KDTree nearest indices: [1, 2] distances: [0.141, 1.421]
Bloom checks: True False
Gotcha Symptom Fix
Missing if d > dist[u]: continue in Dijkstra Duplicate relaxations slow down dense graphs Skip popped entries larger than dist[u]
Negative weights in Dijkstra Wrong shortest path silently returned Use Bellman–Ford (O(VE)O(VE))
Forward loop in 1D 0/1 knapsack Reuses the same item multiple times Loop range(budget, cost - 1, -1)
Forgetting curr[0] = i in 2-row Levenshtein Deletions from the first string are undercounted Initialize curr = [i] + [0] * len(b)
Sorting intervals by start time for scheduling Suboptimal schedule when a long interval starts early Sort by end time ascending
Deterministic last-element pivot in Quickselect O(n2)O(n^2) on sorted inputs Pick pivot uniformly at random
Skipping cycle check in Kahn’s sort Missing tasks when a cycle exists Check len(order) == len(indegree)
Unscaled features in KDTree Large-scale column dominates Euclidean distance Standardize features first
Using built-in hash() in Bloom / MinHash Bit positions change every Python process Use hashlib.sha256 or hashlib.blake2b
Clearing bits to delete from a Bloom filter False negatives for other inserted keys Use a Counting Bloom filter for deletions