45. Algorithms and data structures II
Module 17 gave you the everyday algorithmic toolkit: binary search, sorting, stacks, queues, heaps, hash maps, two pointers and sliding windows. Modern data systems and machine learning libraries go one layer deeper. Every SQL index is a B-tree. Autograd and workflow orchestrators schedule work on directed acyclic graphs. Spellcheckers and sequence aligners rely on 2D dynamic programming. Nearest-neighbor search and streaming deduplication depend on KD-trees, Bloom filters and Locality-Sensitive Hashing. This module shows how these structures work under the hood, why their complexity bounds hold, and how to build and verify them in Python on real course datasets.
What you will learn
Section titled “What you will learn”- Build pointer-based structures (doubly linked lists, LRU caches, tries and Union-Find) and explain amortized complexity.
- Solve weighted shortest-path (Dijkstra), minimum spanning tree (Kruskal) and DAG topological-sort (Kahn) problems on graphs.
- Design 1D and 2D dynamic programming, greedy and divide-and-conquer (Quickselect) algorithms systematically.
- Implement and evaluate data structures used inside ML and data systems: KD-trees, Bloom filters and Locality-Sensitive Hashing (MinHash).
Prerequisites
Section titled “Prerequisites”- 17. Algorithms and data structures: big-O notation, BFS, DFS, heaps, hash maps and memoization.
- 18. Classes and objects: classes, attributes, methods and
__slots__. - 23. NumPy: vectorized arrays and Euclidean norms.
Concepts
Section titled “Concepts”Amortized complexity and space–time trade-offs
Section titled “Amortized complexity and space–time trade-offs”Worst-case big-O looks at a single operation in isolation. That can be misleading. Appending to a Python list usually writes one reference into a free slot in , yet occasionally the backing array fills up and Python allocates a larger array and copies every element in .
Amortized complexity is the average cost per operation over any worst-case sequence of operations. When a dynamic array doubles its capacity at powers of 2 (), the total number of copies across appends is a geometric series:
So appends perform writes plus at most copies — fewer than units of work per append, or amortized.
def simulate_doubling(n: int) -> tuple[int, int, float]: """Return (final capacity, total element copies, average ops per append).""" cap = 1 copies = 0 for size in range(1, n + 1): if size > cap: copies += cap cap *= 2 return cap, copies, (n + copies) / n
for n in (16, 1_024, 65_536): cap, copies, avg = simulate_doubling(n) print(f"n={n:6d}: cap={cap:6d}, copies={copies:6d}, avg_ops={avg:.2f}")n= 16: cap= 16, copies= 15, avg_ops=1.94n= 1024: cap= 1024, copies= 1023, avg_ops=2.00n= 65536: cap= 65536, copies= 65535, avg_ops=2.00Almost every structure in this module trades extra memory for faster queries — a space–time trade-off. A hash map adds bucket storage to turn search into . A dynamic programming table stores subproblem answers to turn exponential recursion into polynomial time. A Bloom filter flips the trade-off: it sacrifices exactness (allowing rare false positives) to shrink memory by 10× or more.
Linked lists and the LRU cache
Section titled “Linked lists and the LRU cache”Python’s list stores elements side by side in memory, which makes lst[i] instant () but removing from the middle because every later element must shift. A doubly linked list connects nodes with prev and next pointers instead. Once you hold a reference to a node, unlinking it or moving it to the front rewires four pointers in with zero shifting.
That property powers an LRU cache (Least Recently Used cache): a fixed-capacity cache that evicts the entry unused for the longest time whenever a new key arrives and the cache is full. Combining two structures gives for both get and put:
- A hash map (
dict) mapskey -> Nodefor lookup. - A doubly linked list (with dummy
headandtailsentinels) keeps the most recently used node right afterheadand the least recently used node right beforetail.
flowchart LR
H["head (sentinel)"] <--> A["P001 (MRU)"]
A <--> B["P015"]
B <--> C["P008 (LRU)"]
C <--> T["tail (sentinel)"]
Sentinel nodes eliminate every None edge case when inserting into an empty list or removing the first or last real element. Python’s collections.OrderedDict and functools.lru_cache use this exact hash-map-plus-linked-list design in C.
Binary search trees, balanced trees and tries
Section titled “Binary search trees, balanced trees and tries”A binary search tree (BST) stores keys so that for every node, every key in its left subtree is smaller and every key in its right subtree is larger. Searching walks left or right at each level, taking where is tree height.
If you insert keys in sorted order (1, 2, 3, ...), a plain BST collapses into a linked list of height and search degrades to . A balanced search tree (such as an AVL tree or a red-black tree) applies local pointer rotations after updates to guarantee in all cases.
Databases take balancing one step further for disk and cache locality. A B-tree lets each node hold hundreds of sorted keys and child pointers instead of just two. Because the branching factor is large, a B-tree storing 100 million SQL rows is only 3 or 4 levels tall, so an index lookup reads only a few disk pages.
For string keys, a Trie (prefix tree) avoids comparing whole strings at each node. Each edge represents one character, and words that share a prefix share the same path from the root. Inserting or searching a string of length takes time, regardless of whether the dictionary holds 30 or 30 million words.
flowchart TD
R["root"] --> C["c"]
R --> W["w"]
C --> O["o"]
O --> T["t -> cotton"]
O --> O2["o -> cookbook"]
W --> I["i -> wireless"]
| Structure | Lookup | Prefix / range query | Ordered traversal | Typical use |
|---|---|---|---|---|
Hash map (dict) |
avg | Not supported | No | Key–value caches, feature lookup |
| Balanced BST (AVL / RB) | Yes | In-memory sorted maps and sets | ||
| B-tree | Yes | SQL indexes, file systems | ||
| Trie | Lexicographical | Autocomplete, IP routing, spellcheck |
Disjoint Set Union (Union-Find)
Section titled “Disjoint Set Union (Union-Find)”Suppose you want to cluster customers who bought the same rare product, or test whether adding a delivery route creates a cycle. You need to maintain a partition of elements into non-overlapping groups with two operations:
find(x): return the representative (root) ofx’s group.union(a, b): merge the groups containingaandb.
A Disjoint Set Union (Union-Find) stores each group as a shallow tree inside a parent dictionary. Two tiny optimizations make every operation run in amortized time — where is the inverse Ackermann function, at most for any input that fits in the universe:
- Path compression: during
find(x), point visited nodes directly toward the root so future lookups take one hop. - Union by rank: always attach the shorter tree under the taller tree’s root so tree height never grows linearly.
class UnionFind: """Disjoint Set Union with path halving and union by rank."""
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]] # path halving 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
uf = UnionFind(["S01", "S02", "S03", "S04", "S05"])for u, v in [("S01", "S02"), ("S02", "S03"), ("S04", "S05")]: uf.union(u, v)print("S01 and S03 connected:", uf.find("S01") == uf.find("S03"))print("S01 and S04 connected:", uf.find("S01") == uf.find("S04"))S01 and S03 connected: TrueS01 and S04 connected: FalseWeighted graphs: Dijkstra’s algorithm and minimum spanning trees
Section titled “Weighted graphs: Dijkstra’s algorithm and minimum spanning trees”In Module 17, BFS found the fewest hops on an unweighted graph. When edges carry non-negative costs (kilometers, latency, shipping fees), BFS breaks because a 3-hop route can be shorter than a 1-hop route.
Dijkstra’s algorithm replaces BFS’s FIFO queue with a min-heap (heapq) keyed by (total_distance, node). At each step it pops the unsettled node with the smallest known distance from the source and relaxes its outgoing edges: if dist[u] + weight < dist[v], update dist[v] and push (new_dist, v) onto the heap. Because every weight is non-negative, the first time a node is popped with its current best distance, that distance is final. Stale heap entries (d > dist[u]) are skipped in . Total runtime is .
A related weighted-graph problem is the minimum spanning tree (MST): given a connected undirected graph, choose edges that connect every node with no cycles and the smallest possible total weight (for instance, laying fiber optic cables or designing a hub-and-spoke supply backbone). Kruskal’s algorithm solves MST cleanly using Union-Find:
- Sort all edges by weight ascending in .
- Scan edges in order; if
uf.union(u, v)returnsTrue(no cycle), add the edge to the MST. - Stop once edges are chosen.
Directed acyclic graphs and topological sort
Section titled “Directed acyclic graphs and topological sort”Data pipelines, feature-store dependencies, Makefile targets and neural-network computation graphs all form a directed acyclic graph (DAG): edges point from prerequisite to dependent, and no path loops back to its starting node.
A topological sort orders the nodes linearly so that for every directed edge , node appears before . Kahn’s algorithm computes a topological sort in while automatically detecting cycles:
- Count each node’s in-degree (number of unmet prerequisites).
- Put all nodes with in-degree
0into a queue. - Pop a ready node, append it to
order, and decrement the in-degree of each neighbor; whenever a neighbor hits0, enqueue it. - If
len(order) < len(nodes), the remaining nodes are locked in a cycle.
flowchart LR
A["load_sales"] --> B["clean_rows"]
B --> C["build_features"]
B --> D["quality_checks"]
C --> E["train_model"]
D --> E
In this pipeline, build_features and quality_checks can run in either order, so a DAG can have several valid topological orders. Sorting the ready nodes before enqueueing makes the schedule completely deterministic.
Dynamic programming: memoization vs. tabulation
Section titled “Dynamic programming: memoization vs. tabulation”Module 17 introduced dynamic programming (DP) for problems with two properties:
- Overlapping subproblems: the same subproblem recurs across many branches.
- Optimal substructure: the optimal answer for a problem can be built from optimal answers to smaller subproblems.
There are two ways to implement any DP recurrence:
| Approach | Direction | Implementation | Strengths | Watch out for |
|---|---|---|---|---|
| Memoization (top-down) | Goal down to base cases | Recursion + @functools.cache |
Only computes reachable states; mirrors math directly | Python recursion limit (~1,000 frames) and hash overhead |
| Tabulation (bottom-up) | Base cases up to goal | Iterative loops filling a list or 2D table | No recursion limit; easy to compress space from to | Must loop in valid dependency order |
Tabulation is the workhorse in production Python because it eliminates stack limits and makes memory compression straightforward. Here is a classic 1D DP: choosing non-adjacent daily promo slots to maximize revenue lift (dp[i] = max(dp[i - 1], dp[i - 2] + lift[i])).
lifts = [12, 25, 18, 30, 10, 28]prev2, prev1 = 0, 0 # O(1) space rolling tabulationfor gain in lifts: prev2, prev1 = prev1, max(prev1, prev2 + gain)print("max non-adjacent promo lift:", prev1)max non-adjacent promo lift: 83Because each state only reads the previous two values (prev1 and prev2), the entire DP table shrinks from memory to .
Sequence DP: Levenshtein edit distance and 0/1 knapsack
Section titled “Sequence DP: Levenshtein edit distance and 0/1 knapsack”Two 2D DP templates cover a huge share of real-world data problems.
Edit distance (Levenshtein distance) measures the minimum number of single-character insertions, deletions or substitutions needed to turn string (length ) into string (length ). Define as the edit distance between a[:i] and b[:j]:
The full table takes time and space, and because row depends only on row , keeping two rows reduces space to .
0/1 knapsack chooses a subset of indivisible items — each with a cost and a value — to maximize total value under a capacity . Each item is taken either 0 or 1 times. Iterating capacity backward from B down to cost lets us collapse the 2D table into a single 1D array without reusing the same item twice:
campaigns = [("Email", 2, 14), ("Search", 3, 22), ("Social", 4, 28), ("Video", 5, 36)]budget = 7dp = [0] * (budget + 1)for _, cost, lift in campaigns: for b in range(budget, cost - 1, -1): # backward loop enforces 0/1 choice dp[b] = max(dp[b], dp[b - cost] + lift)print("max lift for budget 7:", dp[budget])max lift for budget 7: 50Iterating b forward instead of backward turns 0/1 knapsack into unbounded knapsack (where the same campaign can be bought multiple times). That one-direction loop bug is one of the most common DP mistakes.
Greedy algorithms and Quickselect
Section titled “Greedy algorithms and Quickselect”A greedy algorithm makes the locally best decision at each step and never backtracks. Greedy algorithms are fast ( or ), but they only produce optimal answers when the problem has the greedy-choice property — making the local choice never blocks a globally optimal solution.
- Works greedily: Kruskal’s MST (pick cheapest non-cycle edge), Dijkstra with non-negative weights (settle closest node), and interval scheduling (pick the non-overlapping meeting or campaign that finishes earliest, leaving maximum room for the rest).
- Fails greedily: 0/1 knapsack! Choosing the highest value-to-cost ratio first can leave wasted budget that a different pair of items would fill better.
Quickselect applies divide-and-conquer to find the -th smallest element (such as a median or 90th percentile) without sorting the whole array. Like quicksort, it picks a random pivot and partitions the slice into elements < pivot and >= pivot. Unlike quicksort, it recurses into only the one side that contains index :
Choosing the pivot uniformly at random prevents the worst case on already-sorted input. np.partition uses an optimized selection algorithm (Introselect) for the same reason when computing NumPy medians and quantiles.
ML and streaming data structures: KD-trees, Bloom filters and LSH
Section titled “ML and streaming data structures: KD-trees, Bloom filters and LSH”When data lives in geometric space or arrives as a high-volume stream, three specialized structures bridge classic algorithms and ML engineering:
- KD-tree (k-dimensional tree): a binary tree that recursively splits -dimensional points along alternating coordinate axes (median of , then median of , and so on). For nearest-neighbor and radius queries in low dimensions (), a KD-tree prunes entire bounding boxes that cannot beat the current closest point, achieving typical query time instead of brute force. Above ~20 dimensions, the curse of dimensionality forces the search to visit almost every box, so production vector databases switch to approximate methods.
- Bloom filter: a bit array of bits initialized to
0, paired with independent hash functions. Inserting an item sets its bit positions to1. Querying checks all bits: if any bit is0, the item is definitely absent (zero false negatives); if all bits are1, the item is probably present (small false-positive rate ). For expected items and target false-positive rate :
At , a Bloom filter uses only ~9.6 bits (1.2 bytes) per item — regardless of whether the keys are 200-byte URLs or review paragraphs.
- Locality-Sensitive Hashing (LSH) and MinHash: ordinary cryptographic hashes scatter similar inputs across unrelated buckets. LSH does the opposite — similar items collide in the same bucket with high probability. For sets of text shingles (-character substrings), MinHash hashes every shingle with hash functions and keeps the minimum hash value for each function. The probability that two sets share the same minimum hash equals their exact Jaccard similarity :
import hashlib
def shingles(text: str, k: int = 3) -> set[str]: clean = " ".join(text.lower().split()) return {clean[i : i + k] for i in range(max(1, len(clean) - k + 1))}
def minhash_signature(items: set[str], num_hashes: int = 64) -> list[int]: sig = [] for seed in range(num_hashes): best = min( int.from_bytes( hashlib.blake2b(f"{seed}:{g}".encode(), digest_size=8).digest(), "big", ) for g in items ) sig.append(best) return sig
s1 = shingles("Great battery life and fast shipping")s2 = shingles("Great battery life and fast delivery")exact_j = len(s1 & s2) / len(s1 | s2)sig1, sig2 = minhash_signature(s1), minhash_signature(s2)est_j = sum(a == b for a, b in zip(sig1, sig2)) / len(sig1)print(f"exact Jaccard={exact_j:.3f}, MinHash(64)={est_j:.3f}")exact Jaccard=0.634, MinHash(64)=0.656Splitting a 64-value MinHash signature into bands (for example, 16 bands of 4 rows) and hashing each band into buckets lets LSH retrieve near-duplicate candidate pairs in sub-linear time without comparing all document pairs.
Worked examples
Section titled “Worked examples”Example 1 — Build an LRU cache for product price lookups
Section titled “Example 1 — Build an LRU cache for product price lookups”Goal: Implement an LRU cache from scratch with a hash map and doubly linked list, replay all 20,228 product lookups from data/sales.csv, and verify that hit/miss counts match functools.lru_cache exactly.
Step 1 — Define the doubly linked list node and LRU cache
Section titled “Step 1 — Define the doubly linked list node and LRU cache”class _CacheNode: __slots__ = ("key", "val", "prev", "next")
def __init__(self, key: str = "", val: float = 0.0) -> None: self.key = key self.val = val self.prev: _CacheNode | None = None self.next: _CacheNode | None = None
class LRUCache: """O(1) Least Recently Used cache backed by a dict and doubly linked list."""
def __init__(self, capacity: int) -> None: self.capacity = capacity self.nodes: dict[str, _CacheNode] = {} self.head = _CacheNode() self.tail = _CacheNode() self.head.next = self.tail self.tail.prev = self.head self.hits = 0 self.misses = 0
def _unlink(self, node: _CacheNode) -> None: assert node.prev is not None and node.next is not None node.prev.next = node.next node.next.prev = node.prev
def _push_front(self, node: _CacheNode) -> None: first = self.head.next assert first is not None node.prev = self.head node.next = first first.prev = node self.head.next = node
def get(self, key: str) -> float | None: node = self.nodes.get(key) if node is None: self.misses += 1 return None self.hits += 1 self._unlink(node) self._push_front(node) return node.val
def put(self, key: str, val: float) -> None: if key in self.nodes: node = self.nodes[key] node.val = val self._unlink(node) self._push_front(node) return if len(self.nodes) >= self.capacity: lru = self.tail.prev assert lru is not None and lru is not self.head self._unlink(lru) del self.nodes[lru.key] node = _CacheNode(key, val) self._push_front(node) self.nodes[key] = nodeEvery get and put performs at most one dict lookup and four pointer updates — strictly regardless of capacity.
Step 2 — Replay the sales access stream and verify against functools.lru_cache
Section titled “Step 2 — Replay the sales access stream and verify against functools.lru_cache”import csvfrom functools import lru_cache
with open("data/products.csv", newline="", encoding="utf-8") as f: price_db = {r["product_id"]: float(r["unit_price"]) for r in csv.DictReader(f)}
with open("data/sales.csv", newline="", encoding="utf-8") as f: product_stream = [r["product_id"] for r in csv.DictReader(f)]
for cap in (5, 10, 20): cache = LRUCache(cap)
@lru_cache(maxsize=cap) def std_lookup(pid: str) -> float: return price_db[pid]
for pid in product_stream: val = cache.get(pid) if val is None: val = price_db[pid] cache.put(pid, val) assert val == std_lookup(pid)
info = std_lookup.cache_info() assert cache.hits == info.hits and cache.misses == info.misses hit_rate = cache.hits / len(product_stream) * 100 print( f"cap={cap:2d}: hits={cache.hits:5d}, " f"misses={cache.misses:5d}, hit_rate={hit_rate:.1f}%" )cap= 5: hits= 3744, misses=16484, hit_rate=18.5%cap=10: hits= 7675, misses=12553, hit_rate=37.9%cap=20: hits=14978, misses= 5250, hit_rate=74.0%Across 20,228 order lines covering 30 products, caching just two-thirds of the catalog (cap=20) serves 74.0% of lookups from memory because popular items repeat frequently. Our hand-built cache matches Python’s C lru_cache on every single hit and miss.
Common mistakes:
- Forgetting to delete
lru.keyfromself.nodeswhen evictingself.tail.prev, causing a silent memory leak. - Forgetting to move an updated key to the front on
put()when the key already exists.
Example 2 — Product search autocomplete with a Trie
Section titled “Example 2 — Product search autocomplete with a Trie”Goal: Index all 30 product names and categories from data/products.csv in a Trie so prefix queries return sorted matches in time.
Step 1 — Build the Trie and index names and word tokens
Section titled “Step 1 — Build the Trie and index names and word tokens”import re
class TrieNode: __slots__ = ("children", "matches")
def __init__(self) -> None: self.children: dict[str, TrieNode] = {} self.matches: list[str] = []
class ProductTrie: def __init__(self) -> None: self.root = TrieNode()
def insert(self, key: str, label: str) -> None: node = self.root for ch in key.lower(): node = node.children.setdefault(ch, TrieNode()) if label not in node.matches: node.matches.append(label)
def autocomplete(self, prefix: str) -> list[str]: node = self.root for ch in prefix.lower(): if ch not in node.children: return [] node = node.children[ch] results: set[str] = set() stack = [node] while stack: cur = stack.pop() results.update(cur.matches) stack.extend(cur.children.values()) return sorted(results)
trie = ProductTrie()with open("data/products.csv", newline="", encoding="utf-8") as f: for row in csv.DictReader(f): label = f"{row['product_id']}: {row['product']} ({row['category']})" trie.insert(row["product"], label) for token in re.findall(r"[a-z0-9]+", row["product"].lower()): trie.insert(token, label)Indexing both the full product title and each individual word lets a user type "wire" or "ear" and still find Wireless Earbuds.
Step 2 — Run prefix queries
Section titled “Step 2 — Run prefix queries”for prefix in ("wi", "run", "sm", "zz"): hits = trie.autocomplete(prefix) print(f"prefix '{prefix}' ({len(hits)} hits):") for item in hits: print(f" {item}")prefix 'wi' (1 hits): P001: Wireless Earbuds (Electronics)prefix 'run' (3 hits): P014: Running Socks 3-Pack (Clothing) P016: Trail Running Shoes (Sports) P025: The Mindful Runner (Books)prefix 'sm' (2 hits): P003: 55-inch 4K Smart TV (Electronics) P005: Smartwatch Series 5 (Electronics)prefix 'zz' (0 hits):A missing prefix like 'zz' fails on the very first character in without scanning any of the 30 products.
Common mistakes:
- Storing case-sensitive keys so
"Wi"misses"Wireless Earbuds". Always normalize both insert keys and queries with.lower(). - Returning duplicates when a product name contains two tokens sharing the same prefix. Collecting into a
setbefore sorting guarantees unique results.
Example 3 — Route deliveries across stores with Dijkstra’s algorithm and Kruskal’s MST
Section titled “Example 3 — Route deliveries across stores with Dijkstra’s algorithm and Kruskal’s MST”Goal: Find the shortest delivery path from New York (S07) to Seattle (S10) on a weighted highway network of the 12 stores in data/stores.csv, then find the minimum-length backbone connecting all 12 stores.
Step 1 — Load store cities and build the weighted adjacency list
Section titled “Step 1 — Load store cities and build the weighted adjacency list”import heapqimport mathfrom collections import defaultdict
with open("data/stores.csv", newline="", encoding="utf-8") as f: stores = {r["store_id"]: r["city"] for r in csv.DictReader(f)}
# Approximate highway distances (km) between regional store hubsstore_edges = [ ("S01", "S02", 660), ("S01", "S03", 455), ("S01", "S05", 1150), ("S01", "S12", 1610), ("S02", "S10", 2660), ("S02", "S12", 1470), ("S03", "S07", 990), ("S03", "S09", 940), ("S04", "S05", 1275), ("S04", "S12", 1660), ("S05", "S06", 1065), ("S05", "S09", 1255), ("S07", "S08", 345), ("S07", "S09", 150), ("S10", "S11", 1300), ("S11", "S12", 2015),]
adj: dict[str, list[tuple[str, int]]] = defaultdict(list)for u, v, km in store_edges: adj[u].append((v, km)) adj[v].append((u, km))Each undirected highway adds two directed entries to adj, mapping each store ID to (neighbor, distance_km).
Step 2 — Run Dijkstra’s shortest-path algorithm and reconstruct the route
Section titled “Step 2 — Run Dijkstra’s shortest-path algorithm and reconstruct the route”def dijkstra( graph: dict[str, list[tuple[str, int]]], start: str) -> tuple[dict[str, float], dict[str, str]]: dist: dict[str, float] = {start: 0.0} parent: dict[str, str] = {} heap: list[tuple[float, str]] = [(0.0, start)] while heap: d, u = heapq.heappop(heap) if d > dist[u]: continue # skip stale heap entry for v, weight in graph[u]: cand = d + weight if cand < dist.get(v, math.inf): dist[v] = cand parent[v] = u heapq.heappush(heap, (cand, v)) return dist, parent
dists, parents = dijkstra(adj, "S07")route: list[str] = []cur: str | None = "S10"while cur is not None: route.append(cur) cur = parents.get(cur)route.reverse()print(f"Shortest S07 -> S10: {int(dists['S10'])} km")print("Route:", " -> ".join(f"{s} ({stores[s]})" for s in route))Shortest S07 -> S10: 4765 kmRoute: S07 (New York) -> S03 (Detroit) -> S01 (Chicago) -> S02 (Minneapolis) -> S10 (Seattle)Tracking parent[v] = u whenever an edge relaxes lets us walk backward from S10 to S07 in to recover the exact route.
Step 3 — Build the minimum spanning tree with Kruskal’s algorithm
Section titled “Step 3 — Build the minimum spanning tree with Kruskal’s algorithm”uf_mst = UnionFind(list(stores))mst_edges: list[tuple[str, str, int]] = []for u, v, km in sorted(store_edges, key=lambda e: e[2]): if uf_mst.union(u, v): mst_edges.append((u, v, km)) if len(mst_edges) == len(stores) - 1: break
total_mst = sum(km for _, _, km in mst_edges)print( f"MST connects {len(stores)} stores using " f"{len(mst_edges)} links ({total_mst} km)")print("Longest MST link:", mst_edges[-1])MST connects 12 stores using 11 links (10825 km)Longest MST link: ('S11', 'S12', 2015)Kruskal’s algorithm drops the 5 redundant cycles out of 16 links, keeping all 12 cities connected for 10,825 km total.
Common mistakes:
- Forgetting
if d > dist[u]: continuein Dijkstra, which causes redundant relaxations whenever a node is pushed multiple times with improved distances. - Confusing shortest-path trees with MSTs: Dijkstra minimizes distance from one source, whereas Kruskal minimizes total network length across all edges.
Example 4 — Resolve a data pipeline DAG with Kahn’s topological sort
Section titled “Example 4 — Resolve a data pipeline DAG with Kahn’s topological sort”Goal: Schedule the data pipeline stages modeled after data/config.json and data/logs/app.log using Kahn’s algorithm, and confirm that an accidental circular dependency raises ValueError.
Step 1 — Load the pipeline name from data/config.json and run Kahn’s sort
Section titled “Step 1 — Load the pipeline name from data/config.json and run Kahn’s sort”import jsonfrom collections import deque
with open("data/config.json", encoding="utf-8") as f: cfg = json.load(f)
pipeline_deps = { "loader": [], "validator": ["loader"], "cleaner": ["validator"], "feature_builder": ["cleaner"], "model_trainer": ["feature_builder"], "exporter": ["cleaner", "model_trainer"],}
def kahn_sort(deps: dict[str, list[str]]) -> list[str]: """Return a deterministic topological order; raise ValueError on a cycle.""" indegree = {node: 0 for node in deps} children: dict[str, list[str]] = defaultdict(list) for node, prereqs in deps.items(): for pre in prereqs: indegree.setdefault(pre, 0) children[pre].append(node) indegree[node] += 1
queue = deque(sorted(n for n, d in indegree.items() if d == 0)) order: list[str] = [] while queue: u = queue.popleft() order.append(u) unlocked = [] for v in children[u]: indegree[v] -= 1 if indegree[v] == 0: unlocked.append(v) queue.extend(sorted(unlocked))
if len(order) != len(indegree): stuck = sorted(n for n, d in indegree.items() if d > 0) raise ValueError(f"Cycle in stages: {', '.join(stuck)}") return order
print(f"Project {cfg['project']} v{cfg['version']} order:")print(" -> ".join(kahn_sort(pipeline_deps)))Project sales-pipeline v1.4.0 order:loader -> validator -> cleaner -> feature_builder -> model_trainer -> exporterEvery stage runs only after all of its prerequisites finish, matching the real execution trace in data/logs/app.log.
Step 2 — Verify that Kahn’s algorithm catches cycles
Section titled “Step 2 — Verify that Kahn’s algorithm catches cycles”bad_deps = dict(pipeline_deps)bad_deps["validator"] = ["loader", "exporter"] # introduces a cycle
try: kahn_sort(bad_deps)except ValueError as err: print("Caught:", err)Caught: Cycle in stages: cleaner, exporter, feature_builder, model_trainer, validatorloader still has in-degree 0 and finishes, while the five downstream stages deadlock at in-degree 1, triggering the exact ValueError.
Common mistakes:
- Reversing edge direction (
children[node].append(pre)instead ofchildren[pre].append(node)), which produces the reverse execution order. - Silently returning a partial list when
len(order) < len(indegree)instead of raising an error on cycles.
Example 5 — Fix typos in product reviews with Levenshtein edit distance
Section titled “Example 5 — Fix typos in product reviews with Levenshtein edit distance”Goal: Implement 2D dynamic programming Levenshtein distance with memory and map real typos in data/reviews.csv (batery, definately, qualty, recieved, recomend, teh) to their intended dictionary words.
Step 1 — Implement space-optimized Levenshtein distance
Section titled “Step 1 — Implement space-optimized Levenshtein distance”def levenshtein(a: str, b: str) -> int: """Return Levenshtein edit distance between a and b in O(min(|a|, |b|)) space.""" 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): 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]
print("batery -> battery:", levenshtein("batery", "battery"))print("recieved -> received:", levenshtein("recieved", "received"))batery -> battery: 1recieved -> received: 2Notice that recieved -> received costs 2 edits (a deletion plus an insertion, or two substitutions) because standard Levenshtein treats adjacent character swaps as two single-character edits.
Step 2 — Scan data/reviews.csv and correct misspelled review words
Section titled “Step 2 — Scan data/reviews.csv and correct misspelled review words”from collections import Counter
word_counts: Counter[str] = Counter()with open("data/reviews.csv", newline="", encoding="utf-8") as f: for row in csv.DictReader(f): word_counts.update(re.findall(r"[a-z]+", row["text"].lower()))
dictionary = ["battery", "definitely", "quality", "received", "recommend", "the"]typos = ["batery", "definately", "qualty", "recieved", "recomend", "teh"]
for typo in typos: best_dist, best_word = min((levenshtein(typo, w), w) for w in dictionary) count = word_counts[typo] print(f"{typo:<10} (seen {count:2d}x) -> {best_word:<10} (dist={best_dist})")batery (seen 13x) -> battery (dist=1)definately (seen 8x) -> definitely (dist=1)qualty (seen 51x) -> quality (dist=1)recieved (seen 1x) -> received (dist=2)recomend (seen 17x) -> recommend (dist=1)teh (seen 54x) -> the (dist=2)All six real typos in data/reviews.csv map cleanly to their target words. On large vocabularies, you can skip any candidate where abs(len(typo) - len(word)) > max_dist before running DP.
Common mistakes:
- Initializing
curr = [0] * (len(b) + 1)instead ofcurr[0] = i, which undercounts deletions from stringa. - Comparing mixed-case words (
"Battery"vs"battery") without lowercasing first, adding a spurious substitution cost of 1.
Example 6 — Find O(n) house price quantiles with Quickselect
Section titled “Example 6 — Find O(n) house price quantiles with Quickselect”Goal: Compute the exact median and 90th percentile of all 3,000 house prices in data/houses.csv using randomized Quickselect, and compare its comparison count against full sorting.
Step 1 — Implement randomized Quickselect with an operation counter
Section titled “Step 1 — Implement randomized Quickselect with an operation counter”import random
def quickselect(values: list[int], k: int, seed: int = 42) -> tuple[int, int]: """Return (k-th smallest element, comparisons) without mutating values.""" arr = values[:] rng = random.Random(seed) lo, hi = 0, len(arr) - 1 comparisons = 0 while lo < hi: p_idx = rng.randint(lo, hi) pivot = arr[p_idx] arr[p_idx], arr[hi] = arr[hi], arr[p_idx] store = lo for i in range(lo, hi): comparisons += 1 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], comparisons if k < store: hi = store - 1 else: lo = store + 1 return arr[lo], comparisonsStep 2 — Run Quickselect on data/houses.csv and compare against sorting
Section titled “Step 2 — Run Quickselect on data/houses.csv and compare against sorting”with open("data/houses.csv", newline="", encoding="utf-8") as f: house_prices = [int(r["price"]) for r in csv.DictReader(f)]
n_houses = len(house_prices)sorted_prices = sorted(house_prices)
for label, k in [("median", n_houses // 2), ("p90", int(0.9 * (n_houses - 1)))]: val, comps = quickselect(house_prices, k) assert val == sorted_prices[k] ratio = comps / n_houses print(f"{label:6s}: USD {val:>9,} ({comps:,} comparisons, {ratio:.2f}n)")
sort_ref = int(n_houses * math.log2(n_houses))print(f"n log2(n) full sort reference: {sort_ref:,} comparisons")median: USD 376,000 (9,925 comparisons, 3.31n)p90 : USD 848,000 (7,863 comparisons, 2.62n)n log2(n) full sort reference: 34,652 comparisonsQuickselect recovers the exact median (USD 376,000) and 90th percentile (USD 848,000) in roughly comparisons — more than 3× fewer comparisons than an sort.
Common mistakes:
- Always picking the last element as pivot (
p_idx = hi). On already-sorted data that degrades Quickselect to ! - Mutating the caller’s list in place unexpectedly. Copy
arr = values[:]unless in-place mutation is explicitly documented.
Example 7 — Speed up nearest-neighbor house lookup with a KD-tree and deduplicate reviews with a Bloom filter
Section titled “Example 7 — Speed up nearest-neighbor house lookup with a KD-tree and deduplicate reviews with a Bloom filter”Goal: Query nearest-neighbor comparable houses on data/houses.csv using scipy.spatial.KDTree (verified against brute force), then build a bit-array Bloom filter to detect duplicate review texts in data/reviews.csv with zero false negatives.
Step 1 — Nearest-neighbor and radius lookup with scipy.spatial.KDTree
Section titled “Step 1 — Nearest-neighbor and radius lookup with scipy.spatial.KDTree”import numpy as npfrom scipy.spatial import KDTree
with open("data/houses.csv", newline="", encoding="utf-8") as f: house_rows = list(csv.DictReader(f))
coords = np.array( [[float(r["sqft"]), float(r["distance_to_center_km"])] for r in house_rows])coords_std = (coords - coords.mean(axis=0)) / coords.std(axis=0)
kdtree = KDTree(coords_std)dists_kd, idxs_kd = kdtree.query(coords_std[0], k=6) # includes H0001 itselfbrute_idxs = np.argsort(np.linalg.norm(coords_std - coords_std[0], axis=1))[:6]assert np.array_equal(idxs_kd, brute_idxs)
neighbors = [house_rows[i]["house_id"] for i in idxs_kd[1:]]in_ball = kdtree.query_ball_point(coords_std[0], r=0.25)print(f"Query house: {house_rows[0]['house_id']} ({house_rows[0]['neighborhood']})")print("5 nearest comparables:", neighbors)print("Exact match with brute force:", True)print("Houses within standardized radius 0.25:", len(in_ball))Query house: H0001 (Lakeview)5 nearest comparables: ['H2759', 'H2339', 'H2384', 'H0157', 'H2075']Exact match with brute force: TrueHouses within standardized radius 0.25: 58Notice we standardized sqft (range 550–5,710) and distance_to_center_km (range 0.2–20.2) first! Without scaling, Euclidean distance in a KD-tree would ignore distance_to_center_km completely.
Step 2 — Deduplicate data/reviews.csv with a Bloom filter
Section titled “Step 2 — Deduplicate data/reviews.csv with a Bloom filter”class BloomFilter: """Probabilistic set membership filter backed by a bytearray."""
def __init__(self, expected_items: int, fp_rate: float = 0.01) -> None: m = -expected_items * math.log(fp_rate) / (math.log(2) ** 2) self.num_bits = max(64, int(math.ceil(m))) k = int(round((self.num_bits / expected_items) * math.log(2))) self.num_hashes = max(1, k) self.bits = bytearray((self.num_bits + 7) // 8)
def _positions(self, item: str) -> list[int]: digest = hashlib.sha256(item.encode("utf-8")).digest() h1 = int.from_bytes(digest[:8], "big") h2 = int.from_bytes(digest[8:16], "big") | 1 return [(h1 + i * h2) % self.num_bits for i in range(self.num_hashes)]
def add(self, item: str) -> None: for pos in self._positions(item): self.bits[pos // 8] |= 1 << (pos % 8)
def __contains__(self, item: str) -> bool: return all( (self.bits[pos // 8] >> (pos % 8)) & 1 for pos in self._positions(item) )
with open("data/reviews.csv", newline="", encoding="utf-8") as f: review_texts = [" ".join(r["text"].lower().split()) for r in csv.DictReader(f)]
bloom = BloomFilter(expected_items=len(review_texts), fp_rate=0.01)exact_seen: set[str] = set()exact_dupes = 0bloom_hits = 0false_negatives = 0
for text in review_texts: in_exact = text in exact_seen in_bloom = text in bloom if in_exact: exact_dupes += 1 if not in_bloom: false_negatives += 1 if in_bloom: bloom_hits += 1 exact_seen.add(text) bloom.add(text)
assert false_negatives == 0fp = bloom_hits - exact_dupesprint( f"Bloom size: {len(bloom.bits):,} bytes " f"({bloom.num_bits} bits, {bloom.num_hashes} hashes)")print(f"Exact dupes: {exact_dupes}, Bloom hits: {bloom_hits}, false positives: {fp}")print( f"False negatives: {false_negatives}, " f"empirical FP rate: {fp / len(exact_seen):.4f}")Bloom size: 3,595 bytes (28756 bits, 7 hashes)Exact dupes: 150, Bloom hits: 157, false positives: 7False negatives: 0, empirical FP rate: 0.0025In only 3,595 bytes (~3.5 KB), the Bloom filter catches all 150 exact duplicate reviews with 0 false negatives and only 7 false positives (0.25%, well under our 1% target). In a streaming ingestion pipeline, those 157 flagged reviews are the only ones that need an expensive exact database check.
Common mistakes:
- Skipping feature scaling before building a KD-tree on features with different units.
- Using Python’s built-in
hash()inside a persistent Bloom filter:hash()is randomized per process (PYTHONHASHSEED), so saved filters would not match on restart. Usehashlibinstead.
Pitfalls
Section titled “Pitfalls”| Mistake | Symptom | Fix |
|---|---|---|
Mutating a key’s value in LRU put() without moving it to the front |
Frequently updated keys get evicted too early | Always unlink and push updated nodes to the MRU front |
| Inserting sorted keys into an unbalanced BST | Tree degenerates to depth | Use a balanced tree, bisect on a sorted list, or a database B-tree index |
| Running Dijkstra on a graph with negative edge weights | Wrong shortest distances, no exception | Use Bellman–Ford () whenever negative weights can appear |
Skipping if d > dist[u]: continue in Dijkstra |
Duplicate pops slow down dense graphs | Discard stale priority-queue entries immediately on pop |
Returning order from Kahn’s sort without checking len(order) == len(nodes) |
Cycles fail silently with missing tasks | Raise ValueError whenever any node keeps in-degree > 0 |
Looping 0/1 knapsack capacity forward (range(cost, B + 1)) |
Same item gets selected multiple times | Loop capacity backward (range(B, cost - 1, -1)) |
| Fixed last-element pivot in Quickselect on sorted data | runtime on already-ordered inputs | Pick a random pivot with rng.randint(lo, hi) |
| Building a KD-tree on unscaled or high-dimensional () features | Wrong neighbors or brute-force-like latency | Standardize features first; use LSH or HNSW in high dimensions |
Using hash() in a Bloom filter or MinHash |
Results differ across Python runs | Use hashlib.sha256 or hashlib.blake2b |
Deleting from a standard Bloom filter by clearing bits to 0 |
Introduces false negatives for other keys | Never clear bits; use a Counting Bloom filter if deletions are required |
Where this is used beyond data science
Section titled “Where this is used beyond data science”- Databases and storage engines: PostgreSQL, SQLite and MySQL index tables with B-trees; LSM-tree stores like RocksDB and Cassandra place a Bloom filter in front of every disk file so lookups for missing keys skip disk I/O completely.
- Compilers, build systems and orchestrators:
make, Cargo, Airflow, dbt and PyTorch autograd build a DAG of tasks or tensor operations and run topological sort to find a valid execution order and reject circular dependencies. - Networking and operating systems: IP routing tables use radix tries (compressed tries) for longest-prefix matching; OS page caches and CDNs rely on LRU variants; OSPF routers compute shortest paths with Dijkstra’s algorithm.
- Search engines and deduplication: Web crawlers use Bloom filters to avoid re-fetching billions of visited URLs and MinHash + LSH to cluster near-duplicate web pages before indexing.
Summary
Section titled “Summary”- Amortized complexity averages occasional expensive operations (like dynamic-array doubling) across a sequence, yielding amortized appends and Union-Find operations.
- An LRU cache combines a hash map with a sentinel-bounded doubly linked list for
get,putand eviction. - Balanced trees and B-trees maintain ordered lookups; Tries support string prefix search independent of dictionary size.
- Union-Find tracks dynamic connectivity and powers Kruskal’s MST (); Dijkstra’s algorithm solves non-negative weighted shortest paths in .
- Kahn’s topological sort schedules DAGs in and detects cycles when fewer than nodes are emitted.
- Dynamic programming solves overlapping subproblems via top-down memoization or bottom-up tabulation; two rows suffice for Levenshtein edit distance, and a backward 1D loop solves 0/1 knapsack.
- Greedy algorithms succeed when the greedy-choice property holds (MST, Dijkstra, interval scheduling); Quickselect finds exact medians and quantiles in expected time.
- KD-trees accelerate low-dimensional nearest-neighbor search, Bloom filters test membership in ~1.2 bytes/item with zero false negatives, and MinHash + LSH find near-duplicates without pairwise comparisons.
Self-check questions
Section titled “Self-check questions”Q1. Why does appending elements to a doubling dynamic array cost amortized even though individual resizes cost ?
Answer
Resizes happen only at powers of two (). The total number of copied elements across all resizes is , so appends perform fewer than total writes — less than 2 operations per append on average.
Q2. Why does an LRU cache need a doubly linked list rather than a singly linked list?
Answer
To remove a node from the middle of the list in when get(key) hits or when evicting the tail, you must update node.prev.next = node.next. A singly linked list has no prev pointer, so finding the predecessor would require an scan.
Q3. When is a Trie faster than a hash map, and when is a hash map better?
Answer
A Trie wins on prefix queries (autocomplete("run")), longest-prefix matching and lexicographically ordered walks, because a hash map hashes entire keys and cannot search by prefix. For exact single-key lookups, a hash map is usually faster and more compact in Python.
Q4. How do path compression and union by rank work together in Union-Find?
Answer
Union by rank keeps trees balanced by attaching the shorter tree under the taller root, preventing tall chains. Path compression flattens the tree further on every find() call by linking visited nodes closer to the root. Together they give amortized time per operation.
Q5. Why can Dijkstra’s algorithm give the wrong shortest path if an edge has a negative weight?
Answer
Dijkstra assumes that once the node with the smallest tentative distance is popped from the min-heap, no later path can reach it more cheaply. A negative-weight edge later in the graph can lower the distance to an already-settled node, violating that invariant.
Q6. How does Kahn’s topological sort detect a cycle in a directed graph?
Answer
Nodes inside a cycle (and nodes downstream of a cycle) always have at least one incoming edge from another unvisited node, so their in-degree never drops to 0. When the queue empties, len(order) < len(nodes), proving a cycle exists.
Q7. In the 1D space-optimized 0/1 knapsack loop for b in range(budget, cost - 1, -1):, what goes wrong if you loop forward from cost to budget instead?
Answer
Looping forward reads dp[b - cost] after it was already updated using the current item during the same pass, allowing the same item to be chosen multiple times (unbounded knapsack instead of 0/1 knapsack).
Q8. Why does Quickselect run in expected time whereas Quicksort takes ?
Answer
Quicksort recurses on both partitions (). Quickselect discards the half that does not contain index and recurses on one side only ().
Q9. Why did we standardize sqft and distance_to_center_km before building the KD-tree in Example 7?
Answer
KD-trees measure Euclidean distance across coordinates. Because sqft spans thousands of units while distance_to_center_km spans 0–20, raw distances would be dominated almost entirely by sqft. Standardizing puts both dimensions on comparable scale.
Q10. A Bloom filter returns False for "review_999" and True for "review_1000". What can you conclude for sure about each?
Answer
"review_999" has definitely never been inserted (Bloom filters have zero false negatives). "review_1000" was probably inserted, though there is a small chance of a false positive caused by other items setting the same bits.
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- Exercises: 25 hands-on exercises covering doubly linked lists, LRU caches, tries, Union-Find, Dijkstra, Kruskal, Kahn’s sort, DP, Quickselect, KD-trees, Bloom filters and LSH.
- Mini-project: build the Smart Catalog & Pipeline Engine on
products.csvandreviews.csv. - Cheat sheet: complexity tables, decision guide and copy-ready code templates.
- Next module: 46. Linear algebra in depth dives into matrix transformations, rank, QR projection, eigenvalues and SVD.