45. Algorithms and data structures II — Exercises
These 25 exercises practice every structure and algorithm from module 45. They use the course datasets in data/: products.csv, sales.csv, stores.csv, houses.csv, reviews.csv and web_traffic.csv.
How to work:
- Copy the
Setupimports and the starter block into a script (for exampleexercise.py). - Replace each to-do comment with your own implementation and run it from the folder containing
data/. - Compare your output with the expected output. Open one hint at a time if stuck, and inspect the solution only after a genuine attempt.
Every exercise runs with these standard imports in scope.
import csvimport hashlibimport heapqimport mathimport randomimport refrom collections import Counter, defaultdict, dequeimport numpy as npfrom scipy.spatial import KDTreeWarm-up
Section titled “Warm-up”M45-W01 · Insert and unlink nodes in a doubly linked list
Section titled “M45-W01 · Insert and unlink nodes in a doubly linked list”Write a minimal sentinel-bounded doubly linked list with push_front(val), unlink(node) and to_list(). Insert "P001", "P002", "P003" at the front (saving the "P002" node), print the list, unlink "P002", and print the list again.
before: ['P003', 'P002', 'P001']after: ['P003', 'P001']class Node: __slots__ = ("val", "prev", "next")
def __init__(self, val: str = "") -> None: self.val = val self.prev: Node | None = None self.next: Node | None = None
class DoublyLinkedList: def __init__(self) -> None: self.head = Node() self.tail = Node() self.head.next = self.tail self.tail.prev = self.head
def push_front(self, val: str) -> Node: ... # TODO: insert a new node right after self.head and return it
def unlink(self, node: Node) -> None: ... # TODO: rewire node.prev and node.next to skip node
def to_list(self) -> list[str]: ... # TODO: walk from head.next to tail and return values
# TODO: push P001, P002, P003, print before, unlink P002, print afterHint 1
In push_front, save first = self.head.next, wire node.prev = self.head and node.next = first, then update first.prev = node and self.head.next = node.
Hint 2
In unlink(node), set node.prev.next = node.next and node.next.prev = node.prev. Sentinels guarantee neither neighbor is None.
Solution
class Node: __slots__ = ("val", "prev", "next")
def __init__(self, val: str = "") -> None: self.val = val self.prev: Node | None = None self.next: Node | None = None
class DoublyLinkedList: def __init__(self) -> None: self.head = Node() self.tail = Node() self.head.next = self.tail self.tail.prev = self.head
def push_front(self, val: str) -> Node: node = Node(val) first = self.head.next assert first is not None node.prev = self.head node.next = first first.prev = node self.head.next = node return node
def unlink(self, node: Node) -> None: assert node.prev is not None and node.next is not None node.prev.next = node.next node.next.prev = node.prev
def to_list(self) -> list[str]: out: list[str] = [] cur = self.head.next while cur is not None and cur is not self.tail: out.append(cur.val) cur = cur.next return out
dll = DoublyLinkedList()dll.push_front("P001")mid = dll.push_front("P002")dll.push_front("P003")before = dll.to_list()dll.unlink(mid)after = dll.to_list()print("before:", before)print("after:", after)assert before == ["P003", "P002", "P001"]assert after == ["P003", "P001"]before: ['P003', 'P002', 'P001']after: ['P003', 'P001']How it works:
- Dummy
headandtailsentinels mean every real node always has validprevandnextneighbors. - Both
push_frontandunlinkperform four pointer assignments in .
M45-W02 · Count words sharing a prefix in a Trie
Section titled “M45-W02 · Count words sharing a prefix in a Trie”Build a Trie that stores a pass_count on every node (incremented each time an inserted word passes through that character) so count_prefix(prefix) answers in without walking the subtree. Insert the six words below and print counts for "co", "ca", "w" and "z".
co: 2, ca: 1, w: 2, z: 0words = ["cotton", "cookbook", "camping", "wireless", "waterproof", "earbuds"]
# TODO: implement TrieNode(children, pass_count), insert(), and count_prefix()Hint 1
When inserting a word, increment node.pass_count += 1 at each child node you step into.
Hint 2
In count_prefix(prefix), walk character by character; return 0 as soon as a character is missing, otherwise return node.pass_count.
Solution
class CountNode: __slots__ = ("children", "pass_count")
def __init__(self) -> None: self.children: dict[str, CountNode] = {} self.pass_count = 0
class PrefixCounterTrie: def __init__(self) -> None: self.root = CountNode()
def insert(self, word: str) -> None: node = self.root for ch in word.lower(): node = node.children.setdefault(ch, CountNode()) node.pass_count += 1
def count_prefix(self, prefix: str) -> int: node = self.root for ch in prefix.lower(): if ch not in node.children: return 0 node = node.children[ch] return node.pass_count
words = ["cotton", "cookbook", "camping", "wireless", "waterproof", "earbuds"]trie = PrefixCounterTrie()for w in words: trie.insert(w)
counts = {p: trie.count_prefix(p) for p in ("co", "ca", "w", "z")}print(", ".join(f"{k}: {v}" for k, v in counts.items()))assert counts == {"co": 2, "ca": 1, "w": 2, "z": 0}co: 2, ca: 1, w: 2, z: 0How it works:
- Storing
pass_counton every traversed node precomputes subtree sizes during insertion. - Prefix counts now take time instead of scanning every matching word in the subtree.
M45-W03 · Count connected components with Union-Find
Section titled “M45-W03 · Count connected components with Union-Find”Seven warehouses (W1..W7) are linked by four bidirectional routes: ("W1", "W2"), ("W2", "W3"), ("W4", "W5"), ("W1", "W3"). Use Union-Find to process the routes, report how many routes were redundant (already connected), and print the sorted list of connected components.
redundant links: 1components: [['W1', 'W2', 'W3'], ['W4', 'W5'], ['W6'], ['W7']]nodes = [f"W{i}" for i in range(1, 8)]links = [("W1", "W2"), ("W2", "W3"), ("W4", "W5"), ("W1", "W3")]
# TODO: build Union-Find, count redundant links, group nodes by rootHint 1
Have union(a, b) return False when find(a) == find(b). Count how many times union returns False.
Hint 2
After processing all links, group nodes with groups[find(x)].append(x) and sort the groups.
Solution
nodes = [f"W{i}" for i in range(1, 8)]links = [("W1", "W2"), ("W2", "W3"), ("W4", "W5"), ("W1", "W3")]
parent = {x: x for x in nodes}rank = {x: 0 for x in nodes}
def find(x: str) -> str: while parent[x] != x: parent[x] = parent[parent[x]] x = parent[x] return x
def union(a: str, b: str) -> bool: ra, rb = find(a), find(b) if ra == rb: return False if rank[ra] < rank[rb]: ra, rb = rb, ra parent[rb] = ra if rank[ra] == rank[rb]: rank[ra] += 1 return True
redundant = sum(not union(u, v) for u, v in links)groups: dict[str, list[str]] = defaultdict(list)for x in nodes: groups[find(x)].append(x)components = sorted(sorted(g) for g in groups.values())
print("redundant links:", redundant)print("components:", components)assert redundant == 1assert len(components) == 4redundant links: 1components: [['W1', 'W2', 'W3'], ['W4', 'W5'], ['W6'], ['W7']]How it works:
("W1", "W3")findsW1andW3already share a root viaW2, sounion()returnsFalse.- Four components remain: the triangle
{W1, W2, W3}, the pair{W4, W5}, and isolated nodesW6andW7.
M45-W04 · Build a weighted store adjacency list
Section titled “M45-W04 · Build a weighted store adjacency list”Read data/stores.csv, build an undirected weighted adjacency list from the regional links below, and print the store with the highest degree (most neighbors) along with its sorted neighbors and total outgoing link distance.
hub: S01 (Chicago), degree=4, neighbors=['S02', 'S03', 'S05', 'S12'], sum_km=3875links = [ ("S01", "S02", 660), ("S01", "S03", 455), ("S01", "S05", 1150), ("S01", "S12", 1610), ("S07", "S08", 345), ("S07", "S09", 150),]# TODO: load city names from data/stores.csv, build adjacency dict, find highest-degree hubHint 1
Because the routes are undirected, add (v, km) to adj[u] and (u, km) to adj[v].
Hint 2
Use max(adj, key=lambda s: (len(adj[s]), -int(s[1:]))) to pick the highest-degree store deterministically.
Solution
with open("data/stores.csv", newline="", encoding="utf-8") as f: cities = {r["store_id"]: r["city"] for r in csv.DictReader(f)}
links = [ ("S01", "S02", 660), ("S01", "S03", 455), ("S01", "S05", 1150), ("S01", "S12", 1610), ("S07", "S08", 345), ("S07", "S09", 150),]
adj: dict[str, list[tuple[str, int]]] = defaultdict(list)for u, v, km in links: adj[u].append((v, km)) adj[v].append((u, km))
hub = max(adj, key=lambda s: (len(adj[s]), -int(s[1:])))nbs = sorted(v for v, _ in adj[hub])sum_km = sum(km for _, km in adj[hub])print( f"hub: {hub} ({cities[hub]}), degree={len(nbs)}, " f"neighbors={nbs}, sum_km={sum_km}")assert hub == "S01" and sum_km == 3875hub: S01 (Chicago), degree=4, neighbors=['S02', 'S03', 'S05', 'S12'], sum_km=3875How it works:
- Each undirected link adds two directed tuples to
adj, preserving edge weights for Dijkstra or Prim. S01(Chicago) has degree 4 and total incident link distance 3,875 km.
M45-W05 · Predict the output: Kahn’s topological sort order
Section titled “M45-W05 · Predict the output: Kahn’s topological sort order”Predict the output: trace the deque step by step for the DAG below (where deps[task] lists prerequisites, and newly ready nodes are pushed in alphabetical order). Write down the exact list printed before running the code.
Acceptance criteria:
- Write down the exact list printed by
print(order)before running the code. - Your prediction matches the Output block inside the Solution.
deps = { "load": [], "schema": ["load"], "impute": ["load"], "scale": ["impute"], "train": ["schema", "scale"],}# Trace Kahn's algorithm with a FIFO deque and sorted tie-breaking.# What exact list does print(order) display?Hint 1
At step 1, only "load" has in-degree 0. Removing "load" drops both "impute" and "schema" to in-degree 0.
Hint 2
Because newly ready nodes are pushed alphabetically, "impute" enters the queue before "schema". When "impute" pops, "scale" is appended to the back of the FIFO deque — behind "schema".
Solution
deps = { "load": [], "schema": ["load"], "impute": ["load"], "scale": ["impute"], "train": ["schema", "scale"],}
indeg = {u: 0 for u in deps}fwd: dict[str, list[str]] = defaultdict(list)for u, prereqs in deps.items(): for p in prereqs: fwd[p].append(u) indeg[u] += 1
q = deque(sorted(u for u, d in indeg.items() if d == 0))order: list[str] = []while q: u = q.popleft() order.append(u) unlocked = [] for v in fwd[u]: indeg[v] -= 1 if indeg[v] == 0: unlocked.append(v) q.extend(sorted(unlocked))
print(order)assert order == ["load", "impute", "schema", "scale", "train"]['load', 'impute', 'schema', 'scale', 'train']How it works:
- Initially
q = ['load']. Popping'load'unlocks'impute'and'schema'(sorted), soq = ['impute', 'schema']. - Popping
'impute'unlocks'scale'and appends it at the right, soq = ['schema', 'scale']. - Popping
'schema'leaves'train'at in-degree 1; popping'scale'unlocks'train', giving['load', 'impute', 'schema', 'scale', 'train'].
M45-W06 · Count bundle combinations with 1D bottom-up DP
Section titled “M45-W06 · Count bundle combinations with 1D bottom-up DP”A store sells gift cards in denominations of USD 10, USD 25 and USD 50. Using 1D bottom-up tabulation, count how many unordered combinations of gift cards sum to exactly USD 100 (for example, 50+25+25 and 25+50+25 count as one combination).
combinations for USD 100: 6cards = [10, 25, 50]target = 100# TODO: fill dp[0..target] with dp[0] = 1, iterating outer loop over cardsHint 1
For unordered combinations (like coin change II), loop over each card in the outer loop and amount from card up to target in the inner loop.
Hint 2
The transition is dp[amount] += dp[amount - card] with base case dp[0] = 1.
Solution
cards = [10, 25, 50]target = 100dp = [0] * (target + 1)dp[0] = 1for card in cards: for amount in range(card, target + 1): dp[amount] += dp[amount - card]
print(f"combinations for USD {target}: {dp[target]}")assert dp[target] == 6combinations for USD 100: 6How it works:
- Putting
for card in cards:on the outside ensures combinations are built in non-decreasing card order, preventing duplicate permutations. - The 6 valid combinations are
10×10,5×10 + 2×25,5×10 + 50,4×25,2×25 + 50and2×50.
M45-W07 · Partition prices around a pivot for Quickselect
Section titled “M45-W07 · Partition prices around a pivot for Quickselect”Write the Lomuto partition helper partition(arr, lo, hi, pivot_idx) that moves arr[pivot_idx] to hi, rearranges arr[lo..hi] in place so every element strictly less than the pivot sits to its left, places the pivot in its final slot, and returns that final index. Test it on the list below with pivot_idx = 2 (value 69.99).
pivot_pos=4, left=[19.99, 34.99, 14.99, 59.99], pivot=69.99, right=[79.99, 129.95]prices = [79.99, 19.99, 69.99, 14.99, 129.95, 59.99, 34.99]# TODO: implement Lomuto partition(arr, lo, hi, pivot_idx) and print the resultHint 1
Swap arr[pivot_idx] with arr[hi], initialize store = lo, and loop i from lo to hi - 1. Whenever arr[i] < pivot, swap arr[store] and arr[i] and increment store.
Hint 2
Finish with arr[store], arr[hi] = arr[hi], arr[store] and return store.
Solution
def partition(arr: list[float], lo: int, hi: int, pivot_idx: int) -> int: pivot = arr[pivot_idx] arr[pivot_idx], arr[hi] = arr[hi], arr[pivot_idx] store = 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] return store
prices = [79.99, 19.99, 69.99, 14.99, 129.95, 59.99, 34.99]pos = partition(prices, 0, len(prices) - 1, 2)print( f"pivot_pos={pos}, left={prices[:pos]}, " f"pivot={prices[pos]}, right={prices[pos + 1 :]}")assert pos == 4assert all(x < prices[pos] for x in prices[:pos])assert all(x >= prices[pos] for x in prices[pos + 1 :])pivot_pos=4, left=[19.99, 34.99, 14.99, 59.99], pivot=69.99, right=[79.99, 129.95]How it works:
- One linear scan partitions the slice in time and extra space.
69.99lands at index 4 — its exact sorted position — without sorting either side.
M45-W08 · Fix the bug: Bloom filter bit test
Section titled “M45-W08 · Fix the bug: Bloom filter bit test”Fix the bug: the Bloom filter lookup below returns True for almost every unseen word because two subtle bugs broke its bit test and hash step. Find both bugs, fix them, and verify that "earbuds" and "laptop" return True while "toaster" and "bicycle" return False.
earbuds=True, laptop=True, toaster=False, bicycle=False# BUGGY CODE — fix both bugsm, k = 128, 3bits = bytearray(m // 8)
def positions(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 w in ("earbuds", "laptop"): for p in positions(w): bits[p // 8] |= 1 << (p % 8)
def might_contain(text: str) -> bool: # Bug 1: uses any() instead of all() # Bug 2: shifts left instead of testing bit (p % 8) return any((bits[p // 8] << (p % 8)) & 1 for p in positions(text))Hint 1
A Bloom filter requires every probed bit to be 1 (all(...)), not just one of them (any(...)).
Hint 2
To read bit p % 8 of a byte, shift right (bits[p // 8] >> (p % 8)) before masking with & 1.
Solution
m, k = 128, 3bits = bytearray(m // 8)
def positions(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 w in ("earbuds", "laptop"): for p in positions(w): bits[p // 8] |= 1 << (p % 8)
def might_contain(text: str) -> bool: return all((bits[p // 8] >> (p % 8)) & 1 for p in positions(text))
checks = {w: might_contain(w) for w in ("earbuds", "laptop", "toaster", "bicycle")}print(", ".join(f"{w}={v}" for w, v in checks.items()))assert checks == {"earbuds": True, "laptop": True, "toaster": False, "bicycle": False}earbuds=True, laptop=True, toaster=False, bicycle=FalseHow it works:
- Replacing
anywithallrequires all hash positions to be1. - Right-shifting
>> (p % 8)moves the target bit down into bit position 0 so& 1extracts0or1.
M45-C01 · Implement an LRU cache with an eviction log
Section titled “M45-C01 · Implement an LRU cache with an eviction log”Build an LRUCache(capacity=3) using a dict and doubly linked list (no OrderedDict or functools.lru_cache) that records every evicted key in self.evicted. Replay the sequence of operations below and print the final keys from most-recently-used to least-recently-used plus the eviction log.
mru_to_lru: ['P005', 'P002', 'P004']evicted: ['P001', 'P003']ops = [ ("put", "P001", 79.99), ("put", "P002", 249.0), ("put", "P003", 1299.0), ("get", "P002", None), # refreshes P002; P001 is now LRU ("put", "P004", 1149.0), # evicts P001 ("put", "P002", 239.0), # updates P002 and moves it to MRU ("put", "P005", 199.99), # evicts P003]# TODO: implement LRUCache(capacity=3) with self.evicted and replay opsHint 1
When put(key, val) receives an existing key, update node.val, unlink it, and push it right after head without triggering eviction.
Hint 2
When len(self.nodes) == self.capacity on a brand-new key, evict lru = self.tail.prev, append lru.key to self.evicted, unlink lru, and delete self.nodes[lru.key].
Solution
class _Node: __slots__ = ("key", "val", "prev", "next")
def __init__(self, key: str = "", val: float = 0.0) -> None: self.key, self.val = key, val self.prev: _Node | None = None self.next: _Node | None = None
class LoggedLRUCache: def __init__(self, capacity: int) -> None: self.capacity = capacity self.nodes: dict[str, _Node] = {} self.evicted: list[str] = [] self.head, self.tail = _Node(), _Node() self.head.next, self.tail.prev = self.tail, self.head
def _unlink(self, node: _Node) -> 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: _Node) -> None: first = self.head.next assert first is not None node.prev, node.next = self.head, first first.prev = self.head.next = node
def get(self, key: str) -> float | None: node = self.nodes.get(key) if node is None: return None 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] self.evicted.append(lru.key) node = _Node(key, val) self._push_front(node) self.nodes[key] = node
def keys_mru_to_lru(self) -> list[str]: out, cur = [], self.head.next while cur is not None and cur is not self.tail: out.append(cur.key) cur = cur.next return out
ops = [ ("put", "P001", 79.99), ("put", "P002", 249.0), ("put", "P003", 1299.0), ("get", "P002", None), ("put", "P004", 1149.0), ("put", "P002", 239.0), ("put", "P005", 199.99),]cache = LoggedLRUCache(3)for op, k, v in ops: if op == "put": assert v is not None cache.put(k, v) else: cache.get(k)
order = cache.keys_mru_to_lru()print("mru_to_lru:", order)print("evicted:", cache.evicted)assert order == ["P005", "P002", "P004"]assert cache.evicted == ["P001", "P003"]assert cache.get("P002") == 239.0mru_to_lru: ['P005', 'P002', 'P004']evicted: ['P001', 'P003']How it works:
get("P002")promotesP002to the front, leavingP001at the tail to be evicted whenP004arrives.- Updating
P002to239.0promotes it again, soP003is evicted next whenP005arrives.
M45-C02 · Cluster co-purchased products with Union-Find
Section titled “M45-C02 · Cluster co-purchased products with Union-Find”Load data/sales.csv and group lines by order_id. Take the first 10 multi-line orders (sorted by order_id, each having at least 2 distinct products). Using Union-Find over all 30 products (P001..P030), union every pair of products bought together in those 10 baskets. Print the number of connected components and the sizes of the 5 largest clusters.
components: 20, top 5 cluster sizes: [6, 4, 2, 2, 1]# TODO: read data/sales.csv, collect the first 10 multi-product orders by order_id,# union co-purchased products across P001..P030, and print component count + top 5 sizes.Hint 1
Group into orders: dict[str, set[str]] = defaultdict(set), then take [sorted(p) for _, p in sorted(orders.items()) if len(p) >= 2][:10].
Hint 2
For each basket pids, union pids[0] with every p in pids[1:].
Solution
orders: dict[str, set[str]] = defaultdict(set)with open("data/sales.csv", newline="", encoding="utf-8") as f: for row in csv.DictReader(f): orders[row["order_id"]].add(row["product_id"])
baskets = [sorted(p) for _, p in sorted(orders.items()) if len(p) >= 2][:10]all_products = [f"P{i:03d}" for i in range(1, 31)]parent = {p: p for p in all_products}rank = {p: 0 for p in all_products}
def find(x: str) -> str: while parent[x] != x: parent[x] = parent[parent[x]] x = parent[x] return x
def union(a: str, b: str) -> None: ra, rb = find(a), find(b) if ra == rb: return if rank[ra] < rank[rb]: ra, rb = rb, ra parent[rb] = ra if rank[ra] == rank[rb]: rank[ra] += 1
for basket in baskets: for prod in basket[1:]: union(basket[0], prod)
clusters: dict[str, list[str]] = defaultdict(list)for p in all_products: clusters[find(p)].append(p)
sizes = sorted((len(v) for v in clusters.values()), reverse=True)print(f"components: {len(clusters)}, top 5 cluster sizes: {sizes[:5]}")assert len(clusters) == 20assert sizes[:5] == [6, 4, 2, 2, 1]components: 20, top 5 cluster sizes: [6, 4, 2, 2, 1]How it works:
- Unioning each basket’s products merges transitive co-purchases (if A is bought with B and B with C, all three join one cluster).
- Ten early multi-line baskets link 14 products into four multi-item clusters (sizes 6, 4, 2, 2) alongside 16 singletons.
M45-C03 · Shortest delivery route with Dijkstra path reconstruction
Section titled “M45-C03 · Shortest delivery route with Dijkstra path reconstruction”Using the weighted store graph from Example 3 and city names from data/stores.csv, run Dijkstra’s algorithm starting at Miami (S06) to find the shortest distance and exact city path to San Francisco (S11).
distance: 5840 kmpath: S06 (Miami) -> S05 (Atlanta) -> S01 (Chicago) -> S12 (Denver) -> S11 (San Francisco)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),]# TODO: run Dijkstra from S06, reconstruct path to S11, print distance and city routeHint 1
Store parent[v] = u whenever d + w < dist.get(v, math.inf) and push (d + w, v) into heapq.
Hint 2
Walk backward from "S11" using parent.get(cur) until None, then reverse the list.
Solution
with open("data/stores.csv", newline="", encoding="utf-8") as f: cities = {r["store_id"]: r["city"] for r in csv.DictReader(f)}
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 edges: adj[u].append((v, km)) adj[v].append((u, km))
dist: dict[str, float] = {"S06": 0.0}parent: dict[str, str] = {}pq: list[tuple[float, str]] = [(0.0, "S06")]while pq: d, u = heapq.heappop(pq) if d > dist[u]: continue for v, km in adj[u]: if d + km < dist.get(v, math.inf): dist[v] = d + km parent[v] = u heapq.heappush(pq, (d + km, v))
route: list[str] = []cur: str | None = "S11"while cur is not None: route.append(cur) cur = parent.get(cur)route.reverse()
print(f"distance: {int(dist['S11'])} km")print("path:", " -> ".join(f"{s} ({cities[s]})" for s in route))assert int(dist["S11"]) == 5840assert route == ["S06", "S05", "S01", "S12", "S11"]distance: 5840 kmpath: S06 (Miami) -> S05 (Atlanta) -> S01 (Chicago) -> S12 (Denver) -> S11 (San Francisco)How it works:
- Routing through Chicago (
S05 -> S01 -> S12, 2,760 km) beats Houston (S05 -> S04 -> S12, 2,935 km) by 175 km. - Tracking
parent[v] = uon every relaxation lets us reconstruct the exact 5-city path in .
M45-C04 · Build a regional minimum spanning tree with Kruskal
Section titled “M45-C04 · Build a regional minimum spanning tree with Kruskal”Given the 6 East/North store hubs (S01, S02, S03, S07, S08, S09) and the 7 candidate fiber links below, run Kruskal’s algorithm to select the minimum spanning tree. Print the chosen links in weight order and the total saved length compared to building all 7 links.
chosen: ['S07-S09:150', 'S07-S08:345', 'S01-S03:455', 'S01-S02:660', 'S03-S09:940']mst_km: 2550, saved_km: 2040hubs = ["S01", "S02", "S03", "S07", "S08", "S09"]links = [ ("S01", "S02", 660), ("S01", "S03", 455), ("S03", "S07", 990), ("S03", "S09", 940), ("S07", "S08", 345), ("S07", "S09", 150), ("S02", "S03", 1050),]# TODO: sort links by weight, union endpoints with Union-Find, compute mst_km and saved_kmHint 1
Sort links by key=lambda e: e[2]. Keep an edge only if union(u, v) returns True.
Hint 2
saved_km = sum(w for _, _, w in links) - mst_km.
Solution
hubs = ["S01", "S02", "S03", "S07", "S08", "S09"]links = [ ("S01", "S02", 660), ("S01", "S03", 455), ("S03", "S07", 990), ("S03", "S09", 940), ("S07", "S08", 345), ("S07", "S09", 150), ("S02", "S03", 1050),]parent = {h: h for h in hubs}
def find(x: str) -> str: while parent[x] != x: parent[x] = parent[parent[x]] x = parent[x] return x
chosen = []for u, v, w in sorted(links, key=lambda e: e[2]): ru, rv = find(u), find(v) if ru != rv: parent[rv] = ru chosen.append((u, v, w))
mst_km = sum(w for _, _, w in chosen)saved_km = sum(w for _, _, w in links) - mst_kmprint("chosen:", [f"{u}-{v}:{w}" for u, v, w in chosen])print(f"mst_km: {mst_km}, saved_km: {saved_km}")assert len(chosen) == len(hubs) - 1assert mst_km == 2550 and saved_km == 2040chosen: ['S07-S09:150', 'S07-S08:345', 'S01-S03:455', 'S01-S02:660', 'S03-S09:940']mst_km: 2550, saved_km: 2040How it works:
- Sorting by weight greedily picks the 5 cheapest non-cycling links to connect all 6 hubs.
- The two expensive redundant links
S03-S07(990 km) andS02-S03(1,050 km) are skipped, saving 2,040 km.
M45-C05 · Detect cycles and report blocked tasks in a pipeline DAG
Section titled “M45-C05 · Detect cycles and report blocked tasks in a pipeline DAG”Write schedule_or_report(deps) using Kahn’s algorithm. If the DAG is valid, return ("ok", order). If a cycle exists, return ("cycle", blocked) where blocked is the sorted list of tasks that could never run. Test on both valid_dag and cyclic_dag.
valid: ('ok', ['ingest', 'clean', 'validate', 'publish'])cyclic: ('cycle', ['clean', 'publish', 'validate'])valid_dag = { "ingest": [], "clean": ["ingest"], "validate": ["clean"], "publish": ["validate"],}cyclic_dag = { "ingest": [], "clean": ["ingest", "publish"], "validate": ["clean"], "publish": ["validate"],}# TODO: implement schedule_or_report(deps) and test on both dictsHint 1
Any node whose indegree[node] is still > 0 after the deque empties is either inside a cycle or downstream of one.
Solution
def schedule_or_report(deps: dict[str, list[str]]) -> tuple[str, list[str]]: 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: list[str] = [] 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): blocked = sorted(u for u, d in indeg.items() if d > 0) return "cycle", blocked return "ok", order
valid_dag = { "ingest": [], "clean": ["ingest"], "validate": ["clean"], "publish": ["validate"],}cyclic_dag = { "ingest": [], "clean": ["ingest", "publish"], "validate": ["clean"], "publish": ["validate"],}res_ok = schedule_or_report(valid_dag)res_cyc = schedule_or_report(cyclic_dag)print("valid:", res_ok)print("cyclic:", res_cyc)assert res_ok == ("ok", ["ingest", "clean", "validate", "publish"])assert res_cyc == ("cycle", ["clean", "publish", "validate"])valid: ('ok', ['ingest', 'clean', 'validate', 'publish'])cyclic: ('cycle', ['clean', 'publish', 'validate'])How it works:
- On
cyclic_dag,"ingest"runs normally because it has no prerequisites. - The remaining three stages form a 3-cycle so none reaches in-degree 0, letting the scheduler pinpoint the exact blocked tasks.
M45-C06 · Maximize campaign lift with 0/1 knapsack and item tracking
Section titled “M45-C06 · Maximize campaign lift with 0/1 knapsack and item tracking”A marketing team has a USD 10k budget and 5 candidate campaigns (name, cost_k, expected_lift). Use a 2D 0/1 knapsack table to find both the maximum total lift and the sorted names of the chosen campaigns. Also compare your optimal lift against a greedy strategy that picks highest lift / cost first.
optimal lift: 70, chosen: ['Display', 'Search']greedy lift: 58campaigns = [ ("Email", 2, 13), ("Display", 5, 35), ("Search", 5, 35), ("Social", 6, 45), ("Video", 4, 22),]budget = 10# TODO: build 2D DP table, backtrack chosen names, compare with greedy lift/costHint 1
Let dp[i][b] be the max lift using the first i campaigns with budget b. Compare dp[i - 1][b] (skip) against dp[i - 1][b - cost] + lift (take).
Hint 2
To backtrack from i = len(campaigns), b = budget: if dp[i][b] != dp[i - 1][b], campaign i - 1 was taken, so record its name and subtract its cost from b.
Solution
campaigns = [ ("Email", 2, 13), ("Display", 5, 35), ("Search", 5, 35), ("Social", 6, 45), ("Video", 4, 22),]budget = 10n = len(campaigns)dp = [[0] * (budget + 1) for _ in range(n + 1)]for i, (_, cost, lift) in enumerate(campaigns, start=1): for b in range(budget + 1): dp[i][b] = dp[i - 1][b] if cost <= b: dp[i][b] = max(dp[i][b], dp[i - 1][b - cost] + lift)
chosen: list[str] = []b = budgetfor i in range(n, 0, -1): if dp[i][b] != dp[i - 1][b]: name, cost, _ = campaigns[i - 1] chosen.append(name) b -= costchosen.sort()
# Greedy by lift / cost ratio descendingrem = budgetgreedy_lift = 0for _, cost, lift in sorted(campaigns, key=lambda c: c[2] / c[1], reverse=True): if cost <= rem: rem -= cost greedy_lift += lift
print(f"optimal lift: {dp[n][budget]}, chosen: {chosen}")print(f"greedy lift: {greedy_lift}")assert dp[n][budget] == 70assert chosen == ["Display", "Search"]assert greedy_lift == 58 and greedy_lift < dp[n][budget]optimal lift: 70, chosen: ['Display', 'Search']greedy lift: 58How it works:
- Greedy grabs
Social(ratio 7.5, cost 6, lift 45) first, thenEmail(ratio 6.5, cost 2, lift 13), leaving 2k unspent for a total lift of 58. - Exact 2D DP picks
Display+Search(cost5 + 5 = 10) for a lift of 70, illustrating why 0/1 knapsack requires dynamic programming.
M45-C07 · Reconstruct edit operations for Levenshtein distance
Section titled “M45-C07 · Reconstruct edit operations for Levenshtein distance”Build the full 2D Levenshtein DP table for a = "definately" and b = "definitely", then backtrack from (len(a), len(b)) to (0, 0) to print the edit distance and the exact non-match edit step(s) (format "sub a->e @5", "ins c @3", "del x @2").
distance: 1edits: ['sub a->i @5']a, b = "definately", "definitely"# TODO: fill (len(a)+1) x (len(b)+1) DP table and backtrack the edit operationsHint 1
When backtracking at (i, j): if i > 0 and j > 0 and a[i - 1] == b[j - 1] and dp[i][j] == dp[i - 1][j - 1], move diagonally with no edit.
Hint 2
Otherwise check diagonal substitution (dp[i][j] == dp[i - 1][j - 1] + 1), up deletion (dp[i][j] == dp[i - 1][j] + 1), or left insertion (dp[i][j] == dp[i][j - 1] + 1). Reverse the collected list at the end.
Solution
a, b = "definately", "definitely"m, n = len(a), len(b)dp = [[0] * (n + 1) for _ in range(m + 1)]for i in range(m + 1): dp[i][0] = ifor j in range(n + 1): dp[0][j] = j
for i in range(1, m + 1): for j in range(1, n + 1): cost = 0 if a[i - 1] == b[j - 1] else 1 dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost)
edits: list[str] = []i, j = m, nwhile i > 0 or j > 0: if i > 0 and j > 0 and a[i - 1] == b[j - 1] and dp[i][j] == dp[i - 1][j - 1]: i -= 1 j -= 1 elif i > 0 and j > 0 and dp[i][j] == dp[i - 1][j - 1] + 1: edits.append(f"sub {a[i - 1]}->{b[j - 1]} @{i - 1}") i -= 1 j -= 1 elif i > 0 and dp[i][j] == dp[i - 1][j] + 1: edits.append(f"del {a[i - 1]} @{i - 1}") i -= 1 else: edits.append(f"ins {b[j - 1]} @{i}") j -= 1edits.reverse()
print("distance:", dp[m][n])print("edits:", edits)assert dp[m][n] == 1 and edits == ["sub a->i @5"]distance: 1edits: ['sub a->i @5']How it works:
- Unlike the 2-row space-optimized version, keeping the full table lets us trace which transition produced each optimal cell.
- Backtracking identifies the exact typo: substituting
'a'with'i'at index 5.
M45-C08 · Schedule non-overlapping campaigns greedily
Section titled “M45-C08 · Schedule non-overlapping campaigns greedily”Extract the 7 high-spend marketing campaign windows from data/web_traffic.csv (contiguous stretches where marketing_spend > 1500), then add 4 proposed overlapping promotional windows below. Use greedy earliest-finish interval scheduling (allowing a new campaign to start strictly after the previous one ends) to select the maximum number of non-overlapping campaigns. Print how many were extracted from the CSV, the total candidate count, and the maximum non-overlapping schedule size.
csv campaigns: 7, total candidates: 11, max scheduled: 8proposed = [ ("2022-03-15", "2022-03-25"), ("2022-09-01", "2022-09-20"), ("2023-06-10", "2023-06-20"), ("2023-08-01", "2023-08-10"),]# TODO: extract contiguous high-spend (> 1500) date intervals from data/web_traffic.csv,# combine with proposed, sort by end date, and greedily select non-overlapping windows.Hint 1
ISO dates YYYY-MM-DD compare directly as strings, so start > last_end checks strict non-overlap without datetime parsing.
Hint 2
Sort all intervals by key=lambda iv: (iv[1], iv[0]) (earliest finish date first).
Solution
with open("data/web_traffic.csv", newline="", encoding="utf-8") as f: rows = list(csv.DictReader(f))
csv_windows: list[tuple[str, str]] = []start: str | None = Noneprev_date = ""for row in rows: high = float(row["marketing_spend"]) > 1500.0 if high and start is None: start = row["date"] elif not high and start is not None: csv_windows.append((start, prev_date)) start = None prev_date = row["date"]if start is not None: csv_windows.append((start, prev_date))
proposed = [ ("2022-03-15", "2022-03-25"), ("2022-09-01", "2022-09-20"), ("2023-06-10", "2023-06-20"), ("2023-08-01", "2023-08-10"),]candidates = csv_windows + proposedscheduled: list[tuple[str, str]] = []for s, e in sorted(candidates, key=lambda iv: (iv[1], iv[0])): if not scheduled or s > scheduled[-1][1]: scheduled.append((s, e))
print( f"csv campaigns: {len(csv_windows)}, " f"total candidates: {len(candidates)}, " f"max scheduled: {len(scheduled)}")assert len(csv_windows) == 7assert len(scheduled) == 8csv campaigns: 7, total candidates: 11, max scheduled: 8How it works:
- Sorting by end date guarantees each selected campaign frees the calendar as early as possible (the greedy-choice property).
- All 7 short CSV campaigns plus the non-overlapping August 2023 proposed window fit cleanly, while the three long overlapping proposals are skipped.
M45-C09 · Find median and 90th percentile house prices with Quickselect
Section titled “M45-C09 · Find median and 90th percentile house prices with Quickselect”Load all sqft values from data/houses.csv (3,000 houses). Implement randomized quickselect(values, k, seed=42) returning (value, comparisons) and find the 25th, 50th and 75th percentile floor areas (k = int(q * (n - 1))). Verify every quantile against sorted() and print each value and comparison ratio (comps / n).
p25: 1350 sqft (3.04n)p50: 1740 sqft (4.97n)p75: 2210 sqft (2.94n)# TODO: load sqft ints from data/houses.csv, implement randomized quickselect,# compute p25, p50, p75, assert exact match with sorted(), and print value + ratio.Hint 1
Copy arr = values[:] inside quickselect and seed rng = random.Random(seed) so repeated calls stay deterministic.
Hint 2
Count comparisons += 1 inside the Lomuto partition loop for i in range(lo, hi):.
Solution
def quickselect(values: list[int], k: int, seed: int = 42) -> tuple[int, int]: arr = values[:] rng = random.Random(seed) lo, hi = 0, len(arr) - 1 comps = 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): comps += 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], comps if k < store: hi = store - 1 else: lo = store + 1 return arr[lo], comps
with open("data/houses.csv", newline="", encoding="utf-8") as f: sqfts = [int(r["sqft"]) for r in csv.DictReader(f)]
n = len(sqfts)exact_sorted = sorted(sqfts)for name, q in [("p25", 0.25), ("p50", 0.50), ("p75", 0.75)]: k = int(q * (n - 1)) val, comps = quickselect(sqfts, k, seed=42) assert val == exact_sorted[k] print(f"{name}: {val} sqft ({comps / n:.2f}n)")p25: 1350 sqft (3.04n)p50: 1740 sqft (4.97n)p75: 2210 sqft (2.94n)How it works:
- Randomized partitioning discards the irrelevant half at every step, keeping total comparisons near – rather than .
- Every quantile matches
sorted(sqfts)[k]identically.
M45-C10 · Compare KD-tree radius queries against brute force
Section titled “M45-C10 · Compare KD-tree radius queries against brute force”Load sqft, bedrooms and distance_to_center_km from data/houses.csv, standardize each column to mean 0 and std 1, and build a scipy.spatial.KDTree. For the first 50 houses, query all neighbors within radius r = 0.4 using tree.query_ball_point() and verify that every single query returns the exact same set of indices as a brute-force NumPy Euclidean distance scan. Print the total matches across all 50 queries and the average neighbor count.
50 radius queries verified exact: total_matches=3372, avg_neighbors=67.4# TODO: load 3 numeric columns from data/houses.csv, standardize, build KDTree,# compare query_ball_point(X[i], r=0.4) against brute-force norms for i in range(50).Hint 1
Standardize with X = (raw - raw.mean(axis=0)) / raw.std(axis=0).
Hint 2
Brute-force indices within r: np.flatnonzero(np.linalg.norm(X - X[i], axis=1) <= 0.4). Compare as sorted lists or sets.
Solution
with open("data/houses.csv", newline="", encoding="utf-8") as f: raw = np.array( [ [float(r["sqft"]), float(r["bedrooms"]), float(r["distance_to_center_km"])] for r in csv.DictReader(f) ] )
X = (raw - raw.mean(axis=0)) / raw.std(axis=0)tree = KDTree(X)radius = 0.4total_matches = 0
for i in range(50): kd_hits = sorted(tree.query_ball_point(X[i], r=radius)) brute_hits = np.flatnonzero(np.linalg.norm(X - X[i], axis=1) <= radius).tolist() assert kd_hits == brute_hits total_matches += len(kd_hits)
print( f"50 radius queries verified exact: " f"total_matches={total_matches}, avg_neighbors={total_matches / 50:.1f}")assert total_matches > 050 radius queries verified exact: total_matches=3372, avg_neighbors=67.4How it works:
- In 3 standardized dimensions, the KD-tree returns the exact same ball-query sets as exhaustive Euclidean distance checks while pruning distant hyper-rectangles.
- Standardizing ensures
sqft,bedroomsanddistance_to_center_kmcontribute equally to the radius0.4.
M45-C11 · Measure Bloom filter false-positive rate on review IDs
Section titled “M45-C11 · Measure Bloom filter false-positive rate on review IDs”Load all 3,000 review_id strings from data/reviews.csv. Insert the first 1,500 IDs into two Bloom filters configured for target false-positive rates 0.05 and 0.01, then query all 1,500 inserted IDs (to verify 0 false negatives) and all 1,500 unseen IDs (to measure empirical false positives). Print m, k, false negatives and empirical FP rate for both targets.
target=0.05: m=9353, k=4, fn=0, fp=89/1500 (0.0593)target=0.01: m=14378, k=7, fn=0, fp=15/1500 (0.0100)# TODO: split review_ids into [:1500] and [1500:], build Bloom filters for# fp_rate in (0.05, 0.01) using SHA-256 double hashing, verify fn == 0, print stats.Hint 1
Use m = int(math.ceil(-n * math.log(fp_rate) / (math.log(2) ** 2))) and k = max(1, int(round((m / n) * math.log(2)))).
Hint 2
Compute two 64-bit integers from hashlib.sha256(key.encode()).digest(), force h2 |= 1, and probe (h1 + i * h2) % m.
Solution
with open("data/reviews.csv", newline="", encoding="utf-8") as f: review_ids = [r["review_id"] for r in csv.DictReader(f)]
seen, unseen = review_ids[:1500], review_ids[1500:]
def run_bloom(fp_rate: float) -> tuple[int, int, int, int]: n = len(seen) m = int(math.ceil(-n * math.log(fp_rate) / (math.log(2) ** 2))) k = max(1, int(round((m / n) * math.log(2)))) bits = bytearray((m + 7) // 8)
def probes(key: str) -> list[int]: dig = hashlib.sha256(key.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 rid in seen: for p in probes(rid): bits[p // 8] |= 1 << (p % 8)
def has(key: str) -> bool: return all((bits[p // 8] >> (p % 8)) & 1 for p in probes(key))
fn = sum(not has(rid) for rid in seen) fp = sum(has(rid) for rid in unseen) return m, k, fn, fp
for rate in (0.05, 0.01): m, k, fn, fp = run_bloom(rate) emp = fp / len(unseen) print( f"target={rate:.2f}: m={m}, k={k}, fn={fn}, " f"fp={fp}/{len(unseen)} ({emp:.4f})" ) assert fn == 0target=0.05: m=9353, k=4, fn=0, fp=89/1500 (0.0593)target=0.01: m=14378, k=7, fn=0, fp=15/1500 (0.0100)How it works:
- Cutting the target false-positive rate 5× (from 5% to 1%) increases memory by only ~54% (from 9,353 bits to 14,378 bits) while raising from 4 to 7 hashes.
- Both filters have 0 false negatives and closely track their theoretical false-positive rates.
M45-C12 · Choose a structure and count operations: Trie vs. linear prefix scan
Section titled “M45-C12 · Choose a structure and count operations: Trie vs. linear prefix scan”Choose the right structure for high-frequency prefix lookup: load all unique lowercase word tokens from data/products.csv product names. Run the 6 prefix queries ["wi", "co", "sm", "sh", "ru", "zz"] using (a) a linear scan testing word.startswith(prefix) (counting string checks) and (b) a Trie (counting node steps during prefix descent + subtree collection). Assert both return identical matches and print both total step counts.
vocab words: 91, linear checks: 546, trie steps: 70prefixes = ["wi", "co", "sm", "sh", "ru", "zz"]# TODO: extract sorted unique lowercase word tokens from data/products.csv,# compare linear startswith checks vs Trie steps across all 6 prefixes.Hint 1
Extract words with re.findall(r"[a-z0-9]+", row["product"].lower()) into a set, then sort it.
Hint 2
In the Trie query, count 1 step for each prefix character checked plus 1 step for each node popped during the subtree DFS.
Solution
vocab_set: set[str] = set()with open("data/products.csv", newline="", encoding="utf-8") as f: for row in csv.DictReader(f): vocab_set.update(re.findall(r"[a-z0-9]+", row["product"].lower()))vocab = sorted(vocab_set)
trie: dict = {}for word in vocab: node = trie for ch in word: node = node.setdefault(ch, {}) node["$"] = word
prefixes = ["wi", "co", "sm", "sh", "ru", "zz"]linear_checks = 0trie_steps = 0
for pref in prefixes: lin_hits = [] for w in vocab: linear_checks += 1 if w.startswith(pref): lin_hits.append(w)
node = trie found_pref = True for ch in pref: trie_steps += 1 if ch not in node: found_pref = False break node = node[ch] trie_hits: list[str] = [] if found_pref: stack = [node] while stack: cur = stack.pop() trie_steps += 1 for k, v in cur.items(): if k == "$": trie_hits.append(v) else: stack.append(v) trie_hits.sort() assert lin_hits == trie_hits
print( f"vocab words: {len(vocab)}, linear checks: {linear_checks}, " f"trie steps: {trie_steps}")assert trie_steps < linear_checksvocab words: 91, linear checks: 546, trie steps: 70How it works:
- Linear search touches all 91 words on every query (
6 × 91 = 546checks), including misses like"zz". - The Trie skips every unrelated branch immediately, using nearly 8× fewer steps even on a 30-product catalog — and the gap grows linearly with catalog size.
Challenge
Section titled “Challenge”M45-X01 · Detect negative cycles with Bellman-Ford
Section titled “M45-X01 · Detect negative cycles with Bellman-Ford”Implement bellman_ford(nodes, edges, start) that handles negative edge weights in and detects negative cycles reachable from start (by checking whether a -th relaxation pass still improves any distance). Run it on both pricing_graph (has negative rebates, no negative cycle) and arbitrage_graph (contains a negative cycle).
pricing dists: {'A': 0, 'B': 4, 'C': 2, 'D': 1}arbitrage negative cycle: Truenodes = ["A", "B", "C", "D"]pricing_edges = [("A", "B", 4), ("A", "C", 5), ("B", "C", -2), ("C", "D", -1)]arbitrage_edges = [("A", "B", 1), ("B", "C", -3), ("C", "B", 1), ("C", "D", 2)]# TODO: implement bellman_ford(nodes, edges, start) -> (has_neg_cycle, dists)Hint 1
Initialize dist = {u: math.inf for u in nodes} with dist[start] = 0. Repeat len(nodes) - 1 times: for each (u, v, w), if dist[u] + w < dist[v], update dist[v].
Hint 2
Run one more loop over all edges: if any (u, v, w) satisfies dist[u] + w < dist[v], a reachable negative cycle exists.
Solution
def bellman_ford( nodes: list[str], edges: list[tuple[str, str, int]], start: str) -> tuple[bool, dict[str, float]]: dist: dict[str, float] = {u: math.inf for u in nodes} dist[start] = 0.0 for _ in range(len(nodes) - 1): changed = False for u, v, w in edges: if dist[u] + w < dist[v]: dist[v] = dist[u] + w changed = True if not changed: break has_neg_cycle = any(dist[u] + w < dist[v] for u, v, w in edges) return has_neg_cycle, dist
nodes = ["A", "B", "C", "D"]pricing_edges = [("A", "B", 4), ("A", "C", 5), ("B", "C", -2), ("C", "D", -1)]arbitrage_edges = [("A", "B", 1), ("B", "C", -3), ("C", "B", 1), ("C", "D", 2)]
neg1, dist1 = bellman_ford(nodes, pricing_edges, "A")neg2, _ = bellman_ford(nodes, arbitrage_edges, "A")int_dist1 = {k: int(v) for k, v in dist1.items()}print("pricing dists:", int_dist1)print("arbitrage negative cycle:", neg2)assert not neg1 and int_dist1 == {"A": 0, "B": 4, "C": 2, "D": 1}assert neg2 is Truepricing dists: {'A': 0, 'B': 4, 'C': 2, 'D': 1}arbitrage negative cycle: TrueHow it works:
- Any simple shortest path in a graph of nodes uses at most edges, so passes settle all true shortest distances when no negative cycle exists.
- On
arbitrage_edges, the loopB -> C -> Bhas net weight-2, so the -th pass still shrinks distances and flags the cycle.
M45-X02 · Find a shortest warehouse path with A* search
Section titled “M45-X02 · Find a shortest warehouse path with A* search”A warehouse robot navigates a 6×7 grid where # marks shelves and . marks open aisles, moving 4-directionally (cost 1 per step). Implement A* search with the admissible Manhattan distance heuristic abs(r1 - r2) + abs(c1 - c2) from (0, 0) to (5, 6), and compare the number of popped nodes against uniform Dijkstra (h = 0). Verify both find the same shortest path length.
shortest steps: 11, A* pops: 20, Dijkstra pops: 25grid = [ "...#...", ".#.#.#.", ".#...#.", ".###.#.", ".....#.", ".###...",]# TODO: implement astar(grid, start, goal, use_heuristic=True) returning (steps, pops)Hint 1
Store (f_score, g_score, row, col) in heapq, where f_score = g_score + h(row, col) and g_score is the exact steps taken so far.
Hint 2
Track best_g[(r, c)] and skip popped entries where g > best_g[(r, c)]. Stop as soon as (r, c) == goal.
Solution
grid = [ "...#...", ".#.#.#.", ".#...#.", ".###.#.", ".....#.", ".###...",]
def search_grid( layout: list[str], start: tuple[int, int], goal: tuple[int, int], use_heuristic: bool = True,) -> tuple[int, int]: rows, cols = len(layout), len(layout[0])
def h(r: int, c: int) -> int: return abs(r - goal[0]) + abs(c - goal[1]) if use_heuristic else 0
best_g = {start: 0} pq = [(h(*start), 0, start[0], start[1])] pops = 0 while pq: _, g, r, c = heapq.heappop(pq) if g > best_g[(r, c)]: continue pops += 1 if (r, c) == goal: return g, pops for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)): nr, nc = r + dr, c + dc if 0 <= nr < rows and 0 <= nc < cols and layout[nr][nc] != "#": ng = g + 1 if ng < best_g.get((nr, nc), 10**9): best_g[(nr, nc)] = ng heapq.heappush(pq, (ng + h(nr, nc), ng, nr, nc)) return -1, pops
steps_a, pops_a = search_grid(grid, (0, 0), (5, 6), use_heuristic=True)steps_d, pops_d = search_grid(grid, (0, 0), (5, 6), use_heuristic=False)print(f"shortest steps: {steps_a}, A* pops: {pops_a}, Dijkstra pops: {pops_d}")assert steps_a == steps_d and steps_a > 0assert pops_a < pops_dshortest steps: 11, A* pops: 20, Dijkstra pops: 25How it works:
- Because Manhattan distance never overestimates 4-directional grid distance (it is admissible), A* guarantees the exact same optimal path length as Dijkstra.
- Guiding priority toward the goal cuts expanded nodes significantly compared to Dijkstra’s blind radial expansion.
M45-X03 · Weighted edit distance for keyboard-adjacent typos
Section titled “M45-X03 · Weighted edit distance for keyboard-adjacent typos”Standard Levenshtein charges 1.0 for every substitution. Build weighted_edit(a, b) where substituting two horizontally QWERTY-adjacent letters (such as r/t, i/o, a/s, n/m) costs only 0.5, while all other edits cost 1.0. Compare "qualiry" (adjacent slip r for t) and "qualixy" (non-adjacent slip x for t) against "quality".
qualiry -> quality: 0.5 (plain 1), qualixy -> quality: 1.0 (plain 1)QWERTY_ROWS = ["qwertyuiop", "asdfghjkl", "zxcvbnm"]# TODO: build a set of horizontally adjacent key pairs, then write weighted_edit_distance(a, b)Hint 1
Build adj_pairs = {(row[i], row[i + 1]) for row in QWERTY_ROWS for i in range(len(row) - 1)} plus the reversed pairs (b, a).
Hint 2
In the DP recurrence, set sub_cost = 0.0 if ca == cb else (0.5 if (ca, cb) in adj_pairs else 1.0).
Solution
QWERTY_ROWS = ["qwertyuiop", "asdfghjkl", "zxcvbnm"]ADJACENT: set[tuple[str, str]] = set()for row in QWERTY_ROWS: for i in range(len(row) - 1): ADJACENT.add((row[i], row[i + 1])) ADJACENT.add((row[i + 1], row[i]))
def weighted_edit(a: str, b: str, weighted: bool = True) -> float: prev = [float(j) for j in range(len(b) + 1)] for i, ca in enumerate(a, start=1): curr = [float(i)] + [0.0] * len(b) for j, cb in enumerate(b, start=1): if ca == cb: sub = 0.0 elif weighted and (ca, cb) in ADJACENT: sub = 0.5 else: sub = 1.0 curr[j] = min(prev[j] + 1.0, curr[j - 1] + 1.0, prev[j - 1] + sub) prev = curr return prev[-1]
d1 = weighted_edit("qualiry", "quality")p1 = int(weighted_edit("qualiry", "quality", False))d2 = weighted_edit("qualixy", "quality")p2 = int(weighted_edit("qualixy", "quality", False))print( f"qualiry -> quality: {d1:.1f} (plain {p1}), " f"qualixy -> quality: {d2:.1f} (plain {p2})")assert d1 == 0.5 and d2 == 1.0 and p1 == p2 == 1qualiry -> quality: 0.5 (plain 1), qualixy -> quality: 1.0 (plain 1)How it works:
- Only the substitution cost changes inside the exact same 2-row DP recurrence.
- Plain edit distance ties both strings at 1, whereas keyboard-aware weighting scores the adjacent finger slip
'r' -> 't'(0.5) ahead of the distant typo'x' -> 't'(1.0).
M45-X04 · Find near-duplicate reviews with MinHash and LSH
Section titled “M45-X04 · Find near-duplicate reviews with MinHash and LSH”Load the first 400 rows of data/reviews.csv. Turn each normalized review text into 4-character shingles, build a 32-hash MinHash signature (using hashlib.blake2b with seeds 0..31), and index signatures into LSH using 8 bands of 4 rows each. Collect unique candidate pairs colliding in any band, verify their exact Jaccard similarity >= 0.8, and compare LSH’s recall and candidate count against the brute-force check over all 400 * 399 / 2 = 79,800 pairs.
pairs=79800, lsh_candidates=183, verified=9, exact=9, recall=1.00# TODO: load first 400 reviews from data/reviews.csv, compute 4-char shingles,# 32-hash MinHash signatures, 8x4 LSH banding, verify Jaccard >= 0.8 vs brute force.Hint 1
Hash each (band_index, tuple(sig[b * 4 : (b + 1) * 4])) into buckets[key].append(doc_idx). Every pair of indices sharing a bucket becomes a candidate pair.
Hint 2
With 8 bands of 4 rows, a pair with Jaccard collides in at least one band with probability , while collides with probability only .
Solution
with open("data/reviews.csv", newline="", encoding="utf-8") as f: texts = [" ".join(r["text"].lower().split()) for r in csv.DictReader(f)][:400]
shingles = [ {t[i : i + 4] for i in range(max(1, len(t) - 3))} for t in texts]
num_hashes = 32sigs: list[list[int]] = []for s in shingles: 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 s ) sig.append(best) sigs.append(sig)
bands, rows_per_band = 8, 4buckets: dict[tuple[int, tuple[int, ...]], list[int]] = defaultdict(list)for idx, sig in enumerate(sigs): for b in range(bands): key = (b, tuple(sig[b * rows_per_band : (b + 1) * rows_per_band])) buckets[key].append(idx)
candidates: set[tuple[int, int]] = set()for group in buckets.values(): if len(group) > 1: for i in range(len(group)): for j in range(i + 1, len(group)): candidates.add((group[i], group[j]))
def jaccard(i: int, j: int) -> float: return len(shingles[i] & shingles[j]) / len(shingles[i] | shingles[j])
verified = sum(jaccard(i, j) >= 0.8 for i, j in candidates)exact = sum( jaccard(i, j) >= 0.8 for i in range(len(shingles)) for j in range(i + 1, len(shingles)))total_pairs = len(shingles) * (len(shingles) - 1) // 2recall = verified / exactprint( f"pairs={total_pairs}, lsh_candidates={len(candidates)}, " f"verified={verified}, exact={exact}, recall={recall:.2f}")assert len(candidates) < total_pairs // 100assert verified == exactpairs=79800, lsh_candidates=183, verified=9, exact=9, recall=1.00How it works:
- Banding creates an S-curve collision probability: high-similarity pairs almost always share at least one 4-row band, while dissimilar pairs almost never do.
- LSH trims 79,800 pairwise comparisons down to just 183 candidates (a 436× reduction) while recovering 100% of near-duplicate review pairs.
M45-X05 · Simulate amortized dynamic-array doubling vs. fixed growth
Section titled “M45-X05 · Simulate amortized dynamic-array doubling vs. fixed growth”Compare two dynamic-array growth strategies over n = 10_000 appends: (a) doubling (cap *= 2, amortized) and (b) fixed increment (cap += 100, amortized because resizing happens times). Count total element copies and average work per append (n + copies) / n for both strategies and assert that doubling stays under 3.0 ops/append while fixed growth exceeds 50 ops/append.
doubling (n=10000): resizes=14, copies=16383, avg_ops=2.64fixed+100 (n=10000): resizes=100, copies=495100, avg_ops=50.51# TODO: simulate n = 10_000 appends starting from cap = 1 for doubling vs cap += 100,# count resizes, total copies, and avg_ops = (n + copies) / n.Hint 1
Whenever size > cap, add cap to copies (every existing element must move to the new buffer), increment resizes, and grow cap.
Hint 2
For fixed increment step = 100, start cap = 100 (or cap = 1 then cap += 100). Let’s start both at cap = 1 for a fair comparison.
Solution
def run_growth(n: int, mode: str) -> tuple[int, int, float]: cap = 1 resizes = 0 copies = 0 for size in range(1, n + 1): if size > cap: copies += cap resizes += 1 cap = cap * 2 if mode == "double" else cap + 100 return resizes, copies, (n + copies) / n
n = 10_000r_d, c_d, avg_d = run_growth(n, "double")r_f, c_f, avg_f = run_growth(n, "fixed")print(f"doubling (n={n}): resizes={r_d}, copies={c_d}, avg_ops={avg_d:.2f}")print(f"fixed+100 (n={n}): resizes={r_f}, copies={c_f}, avg_ops={avg_f:.2f}")assert avg_d < 3.0 and avg_f > 50.0doubling (n=10000): resizes=14, copies=16383, avg_ops=2.64fixed+100 (n=10000): resizes=100, copies=495100, avg_ops=50.51How it works:
- Geometric growth (
cap *= 2) resizes only times, keeping total copies under ( amortized per append). - Additive growth (
cap += 100) copies an arithmetic progression , turning appends into total work.