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.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Complexity |
|---|---|---|
| cache hot lookups with fixed capacity | LRUCache (dict + doubly linked list) or @lru_cache |
get / put |
| autocomplete strings by prefix | Trie (character tree) |
|
| maintain connected components / groups | UnionFind (path compression + rank) |
|
| find shortest path with non-negative weights | Dijkstra (heapq min-heap) |
|
| find shortest path with negative weights | Bellman–Ford (relax edges times) | |
| connect all nodes at minimum total cost | Kruskal’s MST (sort edges + UnionFind) |
|
| order tasks with prerequisites and catch cycles | Kahn’s topological sort (in-degree + deque) |
|
| count ways / maximize score over prefixes | 1D bottom-up DP tabulation | |
| measure string similarity / fix typos | Levenshtein edit distance (2-row DP) | time, space |
| maximize value under a fixed budget (each item once) | 0/1 knapsack (backward 1D DP loop) | time, space |
| schedule max non-overlapping intervals | Greedy: sort by finish time ascending | |
| find exact median or -th smallest without sorting | Randomized Quickselect (or np.partition) |
expected |
| query nearest neighbors in low dimensions () | scipy.spatial.KDTree on scaled features |
typical query |
| test set membership in ~1.2 bytes/item | BloomFilter (bit array + double hashing) |
time, 0% FN |
| estimate Jaccard similarity / find near-duplicates | MinHash + LSH banding | per sketch |
Complexity summary
Section titled “Complexity summary”| Structure / Algorithm | Build | Query / Update | Space | Key precondition / note |
|---|---|---|---|---|
| Doubly linked list | with node ref | Sentinels remove None edge cases |
||
| LRU cache | Hash map + doubly linked list | |||
| Balanced BST (AVL / RB) | Keeps sorted order | |||
| B-tree | High branching factor for disk pages | |||
| Trie | Independent of dictionary count | |||
| Union-Find | Path compression + union by rank | |||
| Dijkstra | — | Non-negative edge weights only | ||
| Kruskal MST | — | Undirected weighted graph | ||
| Kahn topological sort | — | Detects cycles when len(order) < V |
||
| Levenshtein DP | — | Two rolling rows | ||
| 0/1 Knapsack | — | Iterate capacity backward | ||
| Quickselect | — | expected | extra | Random pivot avoids |
| KD-tree | low- | Scale features; degrades for | ||
| Bloom filter | bits | No deletions; 0 false negatives | ||
| MinHash | compare | Unbiased estimator of Jaccard |
LRU cache and Trie
Section titled “LRU cache and Trie”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 LRUcache.put("P003", 1299.0) # evicts P002print(list(cache.data.keys()))['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"))['waterproof', 'weeknight', 'wireless', 'wool'] ['wireless']Union-Find, Dijkstra, Kruskal and Kahn’s sort
Section titled “Union-Find, Dijkstra, Kruskal and Kahn’s sort”import heapqimport mathfrom 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 Adist = {"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 MSTuf = 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)Dijkstra D: 8 MST cost: 8def 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"]}))['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))edit: 1knapsack: 36intervals: [(2, 3), (3, 5), (5, 7)]median: 30KD-trees, Bloom filters and MinHash
Section titled “KD-trees, Bloom filters and MinHash”import hashlibimport numpy as npfrom 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, 3bits = 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"))KDTree nearest indices: [1, 2] distances: [0.141, 1.421]Bloom checks: True FalseGotchas
Section titled “Gotchas”| 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 () |
| 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 | 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 |