Skip to content

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.

  • Build pointer-based structures (doubly linked lists, LRU caches, tries and Union-Find) and explain amortized O(1)O(1) 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).

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 O(1)O(1), yet occasionally the backing array fills up and Python allocates a larger array and copies every element in O(n)O(n).

Amortized complexity is the average cost per operation over any worst-case sequence of nn operations. When a dynamic array doubles its capacity at powers of 2 (1,2,4,8,…,n1, 2, 4, 8, \dots, n), the total number of copies across nn appends is a geometric series:

1+2+4+⋯+n2=n−11 + 2 + 4 + \dots + \frac{n}{2} = n - 1

So nn appends perform nn writes plus at most n−1n - 1 copies — fewer than 22 units of work per append, or O(1)O(1) 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}")
Output
n= 16: cap= 16, copies= 15, avg_ops=1.94
n= 1024: cap= 1024, copies= 1023, avg_ops=2.00
n= 65536: cap= 65536, copies= 65535, avg_ops=2.00

Almost every structure in this module trades extra memory for faster queries — a space–time trade-off. A hash map adds bucket storage to turn O(n)O(n) search into O(1)O(1). 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.

Python’s list stores elements side by side in memory, which makes lst[i] instant (O(1)O(1)) but removing from the middle O(n)O(n) 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 O(1)O(1) 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 O(1)O(1) for both get and put:

  • A hash map (dict) maps key -> Node for O(1)O(1) lookup.
  • A doubly linked list (with dummy head and tail sentinels) keeps the most recently used node right after head and the least recently used node right before tail.
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 O(h)O(h) where hh is tree height.

If you insert keys in sorted order (1, 2, 3, ...), a plain BST collapses into a linked list of height nn and search degrades to O(n)O(n). A balanced search tree (such as an AVL tree or a red-black tree) applies local pointer rotations after updates to guarantee h=O(log⁡n)h = O(\log n) 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 LL takes O(L)O(L) 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) O(1)O(1) avg Not supported No Key–value caches, feature lookup
Balanced BST (AVL / RB) O(log⁡n)O(\log n) O(log⁡n+k)O(\log n + k) Yes In-memory sorted maps and sets
B-tree O(log⁡Bn)O(\log_B n) O(log⁡Bn+k)O(\log_B n + k) Yes SQL indexes, file systems
Trie O(L)O(L) O(L+matches)O(L + \text{matches}) Lexicographical Autocomplete, IP routing, spellcheck

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) of x’s group.
  • union(a, b): merge the groups containing a and b.

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 O(α(n))O(\alpha(n)) amortized time — where α(n)\alpha(n) is the inverse Ackermann function, at most 44 for any input that fits in the universe:

  1. Path compression: during find(x), point visited nodes directly toward the root so future lookups take one hop.
  2. 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"))
Output
S01 and S03 connected: True
S01 and S04 connected: False

Weighted 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 O(1)O(1). Total runtime is O((V+E)log⁡V)O((V + E) \log V).

A related weighted-graph problem is the minimum spanning tree (MST): given a connected undirected graph, choose V−1V - 1 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:

  1. Sort all edges by weight ascending in O(Elog⁡E)O(E \log E).
  2. Scan edges in order; if uf.union(u, v) returns True (no cycle), add the edge to the MST.
  3. Stop once V−1V - 1 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 u→vu \to v, node uu appears before vv. Kahn’s algorithm computes a topological sort in O(V+E)O(V + E) while automatically detecting cycles:

  1. Count each node’s in-degree (number of unmet prerequisites).
  2. Put all nodes with in-degree 0 into a queue.
  3. Pop a ready node, append it to order, and decrement the in-degree of each neighbor; whenever a neighbor hits 0, enqueue it.
  4. 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:

  1. Overlapping subproblems: the same subproblem recurs across many branches.
  2. 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 O(nm)O(nm) to O(min⁡(n,m))O(\min(n, m)) 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 tabulation
for gain in lifts:
prev2, prev1 = prev1, max(prev1, prev2 + gain)
print("max non-adjacent promo lift:", prev1)
Output
max non-adjacent promo lift: 83

Because each state only reads the previous two values (prev1 and prev2), the entire DP table shrinks from O(n)O(n) memory to O(1)O(1).

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 aa (length mm) into string bb (length nn). Define D[i][j]D[i][j] as the edit distance between a[:i] and b[:j]:

D[i][j]={iif j=0jif i=0min⁡(D[i−1][j]+1,  D[i][j−1]+1,  D[i−1][j−1]+[ai−1≠bj−1])otherwiseD[i][j] = \begin{cases} i & \text{if } j = 0 \\ j & \text{if } i = 0 \\ \min\bigl(D[i-1][j] + 1,\; D[i][j-1] + 1,\; D[i-1][j-1] + [a_{i-1} \ne b_{j-1}]\bigr) & \text{otherwise} \end{cases}

The full table takes O(mn)O(mn) time and space, and because row ii depends only on row i−1i - 1, keeping two rows reduces space to O(min⁡(m,n))O(\min(m, n)).

0/1 knapsack chooses a subset of indivisible items — each with a cost wiw_i and a value viv_i — to maximize total value under a capacity BB. 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 = 7
dp = [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])
Output
max lift for budget 7: 50

Iterating 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.

A greedy algorithm makes the locally best decision at each step and never backtracks. Greedy algorithms are fast (O(nlog⁡n)O(n \log n) or O(n)O(n)), 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 kk-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 kk:

n+n2+n4+⋯≈2n=O(n) expected timen + \frac{n}{2} + \frac{n}{4} + \dots \approx 2n = O(n) \text{ expected time}

Choosing the pivot uniformly at random prevents the O(n2)O(n^2) 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:

  1. KD-tree (k-dimensional tree): a binary tree that recursively splits dd-dimensional points along alternating coordinate axes (median of xx, then median of yy, and so on). For nearest-neighbor and radius queries in low dimensions (d≤15d \le 15), a KD-tree prunes entire bounding boxes that cannot beat the current closest point, achieving O(log⁡n)O(\log n) typical query time instead of O(n)O(n) 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.
  2. Bloom filter: a bit array of mm bits initialized to 0, paired with kk independent hash functions. Inserting an item sets its kk bit positions to 1. Querying checks all kk bits: if any bit is 0, the item is definitely absent (zero false negatives); if all kk bits are 1, the item is probably present (small false-positive rate pp). For nn expected items and target false-positive rate pp:
m=⌈−nln⁡p(ln⁡2)2⌉,k=round ⁣(mnln⁡2)m = \left\lceil -\frac{n \ln p}{(\ln 2)^2} \right\rceil, \qquad k = \text{round}\!\left(\frac{m}{n}\ln 2\right)

At p=1%p = 1\%, 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.

  1. 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 (kk-character substrings), MinHash hashes every shingle with HH 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 ∣A∩B∣/∣A∪B∣|A \cap B| / |A \cup B|:
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}")
Output
exact Jaccard=0.634, MinHash(64)=0.656

Splitting 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 O(n2)O(n^2) document pairs.

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 O(1)O(1) 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] = node

Every get and put performs at most one dict lookup and four pointer updates — strictly O(1)O(1) 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 csv
from 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}%"
)
Output
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.key from self.nodes when evicting self.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 O(L+subtree)O(L + \text{subtree}) 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.

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}")
Output
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 O(1)O(1) 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 set before 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 heapq
import math
from 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 hubs
store_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))
Output
Shortest S07 -> S10: 4765 km
Route: 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 O(V)O(V) 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])
Output
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]: continue in 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 json
from 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)))
Output
Project sales-pipeline v1.4.0 order:
loader -> validator -> cleaner -> feature_builder -> model_trainer -> exporter

Every 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)
Output
Caught: Cycle in stages: cleaner, exporter, feature_builder, model_trainer, validator

loader 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 of children[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 O(min⁡(m,n))O(\min(m, n)) 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"))
Output
batery -> battery: 1
recieved -> received: 2

Notice 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})")
Output
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 of curr[0] = i, which undercounts deletions from string a.
  • 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], comparisons

Step 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")
Output
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 comparisons

Quickselect recovers the exact median (USD 376,000) and 90th percentile (USD 848,000) in roughly 3n3n comparisons — more than 3× fewer comparisons than an O(nlog⁡n)O(n \log n) sort.

Common mistakes:

  • Always picking the last element as pivot (p_idx = hi). On already-sorted data that degrades Quickselect to O(n2)O(n^2)!
  • 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 np
from 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 itself
brute_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))
Output
Query house: H0001 (Lakeview)
5 nearest comparables: ['H2759', 'H2339', 'H2384', 'H0157', 'H2075']
Exact match with brute force: True
Houses within standardized radius 0.25: 58

Notice 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 = 0
bloom_hits = 0
false_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 == 0
fp = bloom_hits - exact_dupes
print(
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}"
)
Output
Bloom size: 3,595 bytes (28756 bits, 7 hashes)
Exact dupes: 150, Bloom hits: 157, false positives: 7
False negatives: 0, empirical FP rate: 0.0025

In 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. Use hashlib instead.
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 O(n)O(n) 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 (O(VE)O(VE)) 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 &gt; 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 O(n2)O(n^2) runtime on already-ordered inputs Pick a random pivot with rng.randint(lo, hi)
Building a KD-tree on unscaled or high-dimensional (d>20d \gt 20) 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
  • 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.
  • Amortized complexity averages occasional expensive operations (like dynamic-array doubling) across a sequence, yielding O(1)O(1) amortized appends and O(α(n))O(\alpha(n)) Union-Find operations.
  • An LRU cache combines a hash map with a sentinel-bounded doubly linked list for O(1)O(1) get, put and eviction.
  • Balanced trees and B-trees maintain O(log⁡n)O(\log n) ordered lookups; Tries support O(L)O(L) string prefix search independent of dictionary size.
  • Union-Find tracks dynamic connectivity and powers Kruskal’s MST (O(Elog⁡E)O(E \log E)); Dijkstra’s algorithm solves non-negative weighted shortest paths in O((V+E)log⁡V)O((V + E) \log V).
  • Kahn’s topological sort schedules DAGs in O(V+E)O(V + E) and detects cycles when fewer than VV 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 O(n)O(n) 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 O(n2)O(n^2) pairwise comparisons.

Q1. Why does appending nn elements to a doubling dynamic array cost O(1)O(1) amortized even though individual resizes cost O(n)O(n)?

Answer

Resizes happen only at powers of two (1,2,4,…,n/21, 2, 4, \dots, n/2). The total number of copied elements across all resizes is 1+2+4+⋯+n/2=n−11 + 2 + 4 + \dots + n/2 = n - 1, so nn appends perform fewer than 2n2n 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 O(1)O(1) 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 O(n)O(n) 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 O(α(n))O(\alpha(n)) 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 O(n)O(n) expected time whereas Quicksort takes O(nlog⁡n)O(n \log n)?

Answer

Quicksort recurses on both partitions (T(n)=2T(n/2)+O(n)=O(nlog⁡n)T(n) = 2T(n/2) + O(n) = O(n \log n)). Quickselect discards the half that does not contain index kk and recurses on one side only (T(n)=T(n/2)+O(n)=O(n)T(n) = T(n/2) + O(n) = O(n)).

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 kk bits.

Your progress

0 / 4 done

  • 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.csv and reviews.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.