Skip to content

Complexity and data structures

This reference pairs Big-O growth classes and amortized rules with the pointer, tree, graph, and probabilistic structures used in engineering and ML systems. Every code block shares one session using data/products.csv and data/houses.csv:

from collections import OrderedDict
import hashlib
import math
import numpy as np
import pandas as pd
from scipy.spatial import KDTree
products = pd.read_csv("data/products.csv")
houses = pd.read_csv("data/houses.csv")
I want to… Use… Complexity
estimate runtime growth for large nn Big-O upper bound on dominant term drop constants and lower-order terms
analyze a structure with rare expensive resizes amortized cost (aggregate or potential method) list.append is O(1)O(1) amortized
O(1) lookup plus O(1) eviction of oldest entry LRU cache (OrderedDict or hash map + doubly linked list) O(1)O(1) get and put
memoize pure function calls in Python @functools.lru_cache(maxsize=256) O(1)O(1) average lookup
prefix search and autocomplete on strings Trie (prefix tree) O(L)O(L) per key of length LL
range queries and ordered iteration balanced BST (AVL / Red-Black) or B-tree O(log⁡n)O(\log n) search, insert, delete
track connected components dynamically Union-Find (DSU) with path compression + rank O(α(n))≈O(1)O(\alpha(n)) \approx O(1) amortized
fast k-NN or radius search in low-D numeric space scipy.spatial.KDTree O(log⁡n)O(\log n) query for d≤20d \le 20
test set membership with tiny fixed memory Bloom filter (bit array + kk hash functions) O(k)O(k) insert/query; no false negatives
find near-duplicate sets or documents at scale MinHash + Locality-Sensitive Hashing (LSH) sublinear candidate lookup
Class Name n=103n = 10^3 ops n=106n = 10^6 ops Typical examples
O(1)O(1) constant 11 11 dict lookup, array index, deque.popleft()
O(α(n))O(\alpha(n)) inverse Ackermann ≤4\le 4 ≤4\le 4 Union-Find with compression and rank
O(log⁡n)O(\log n) logarithmic ≈10\approx 10 ≈20\approx 20 binary search, balanced BST, heap push/pop
O(n)O(n) linear 10310^3 10610^6 single scan, two pointers, Quickselect average, heapify
O(nlog⁡n)O(n \log n) linearithmic 10410^4 2×1072 \times 10^7 Timsort (sorted), mergesort, building KD-tree
O(n2)O(n^2) quadratic 10610^6 101210^{12} nested loops, pairwise distances, 2D DP on n×nn \times n
O(n3)O(n^3) cubic 10910^9 101810^{18} dense matrix multiply (n×nn \times n), Floyd–Warshall
O(2n)O(2^n) exponential intractable intractable brute-force subsets, unmemoized Fibonacci
O(n!)O(n!) factorial intractable intractable brute-force permutations (TSP)

For divide-and-conquer recurrences T(n)=aT(n/b)+O(nd)T(n) = a T(n / b) + O(n^d) (Master Theorem):

Condition Result Example
d>log⁡bad > \log_b a (work at root dominates) T(n)=O(nd)T(n) = O(n^d) Quickselect average (a=1,b=2,d=1⇒O(n)a=1, b=2, d=1 \Rightarrow O(n))
d=log⁡bad = \log_b a (equal work per level) T(n)=O(ndlog⁡n)T(n) = O(n^d \log n) mergesort (a=2,b=2,d=1⇒O(nlog⁡n)a=2, b=2, d=1 \Rightarrow O(n \log n)), binary search (a=1,b=2,d=0⇒O(log⁡n)a=1, b=2, d=0 \Rightarrow O(\log n))
d<log⁡bad < \log_b a (leaves dominate) T(n)=O(nlog⁡ba)T(n) = O(n^{\log_b a}) Karatsuba (a=3,b=2,d=1⇒O(n1.585)a=3, b=2, d=1 \Rightarrow O(n^{1.585}))
Amortized scenario Worst single op Amortized cost Why
dynamic array (list.append) O(n)O(n) on resize O(1)O(1) doubling capacity copies 1+2+4+⋯+n<2n1 + 2 + 4 + \dots + n < 2n items
hash table (dict / set insert) O(n)O(n) on rehash O(1)O(1) load factor capped (≈2/3\approx 2/3 in CPython); doubling spreads rehash cost
monotonic stack / sliding window O(n)O(n) pops in one step O(1)O(1) per item each element enters and leaves the structure at most once
Union-Find (find + union) O(log⁡n)O(\log n) O(α(n))O(\alpha(n)) path compression flattens trees; rank keeps height bounded
binary heap build (heapq.heapify) — O(n)O(n) total bottom-up sifting does most work on shallow subtrees

Average-case time unless marked; nn is items, LL is string length, kk is hash count, dd is dimension.

Structure Lookup / Query Insert Delete Space Best for
list (dynamic array) O(1)O(1) index, O(n)O(n) scan O(1)O(1) end, O(n)O(n) front O(1)O(1) end, O(n)O(n) front O(n)O(n) sequences, stacks, cache-friendly scans
deque (doubly linked blocks) O(1)O(1) ends, O(n)O(n) mid O(1)O(1) both ends O(1)O(1) both ends O(n)O(n) FIFO queues, BFS, fixed windows
dict / set (hash table) O(1)O(1) avg, O(n)O(n) worst O(1)O(1) avg O(1)O(1) avg O(n)O(n) key lookup, deduplication, counting
heapq (binary min-heap) O(1)O(1) min O(log⁡n)O(\log n) O(log⁡n)O(\log n) min O(n)O(n) priority queues, Dijkstra, top-kk
Doubly linked list O(n)O(n) by value O(1)O(1) given node O(1)O(1) given node O(n)O(n) LRU eviction order, splice
Balanced BST / B-tree O(log⁡n)O(\log n) O(log⁡n)O(\log n) O(log⁡n)O(\log n) O(n)O(n) sorted ranges, SQL indexes (B+ tree)
Trie (prefix tree) O(L)O(L) O(L)O(L) O(L)O(L) O(∑L)O(\sum L) autocomplete, prefix counts, IP routing
Union-Find (DSU) O(α(n))O(\alpha(n)) find O(α(n))O(\alpha(n)) union not supported O(n)O(n) connected components, Kruskal MST
KD-tree (low dd) O(log⁡n)O(\log n) avg, O(n)O(n) high dd O(log⁡n)O(\log n) static build O(nlog⁡n)O(n \log n) rebuild O(n)O(n) spatial / low-D nearest neighbors
Bloom filter O(k)O(k) O(k)O(k) not supported (needs counting filter) O(m)O(m) bits memory-tight duplicate / cache guard

An LRU (Least Recently Used) cache combines a hash map (for O(1)O(1) key lookup) with a doubly linked list (for O(1)O(1) move-to-front and tail eviction). In Python, collections.OrderedDict implements this combination in C; for pure functions, functools.lru_cache wraps it as a decorator.

class LRUCache:
"""Fixed-capacity LRU cache with O(1) get and put."""
def __init__(self, capacity: int) -> None:
self.capacity = capacity
self.store: OrderedDict[str, float] = OrderedDict()
self.hits = 0
self.misses = 0
def get(self, key: str) -> float | None:
if key not in self.store:
self.misses += 1
return None
self.hits += 1
self.store.move_to_end(key)
return self.store[key]
def put(self, key: str, value: float) -> None:
if key in self.store:
self.store.move_to_end(key)
self.store[key] = value
if len(self.store) > self.capacity:
self.store.popitem(last=False)
prices = dict(zip(products["product_id"], products["unit_price"]))
cache = LRUCache(capacity=3)
for pid in ["P001", "P002", "P003", "P001", "P004", "P002"]:
if cache.get(pid) is None:
cache.put(pid, prices[pid])
print("keys (LRU -> MRU):", list(cache.store.keys()))
print(f"hits={cache.hits}, misses={cache.misses}")
Output
keys (LRU -> MRU): ['P001', 'P004', 'P002']
hits=1, misses=5
Tree variant Node branching Key property Primary use
Binary Search Tree (BST) 2 children left < node < right; degrades to O(n)O(n) on sorted input teaching baseline
AVL / Red-Black tree 2 children rotations enforce height O(log⁡n)O(\log n) in-memory sorted maps (std::map)
B-tree / B+ tree hundreds of keys per page wide shallow nodes match disk/cache pages; leaves linked PostgreSQL, SQLite, InnoDB indexes
Trie (prefix tree) one edge per character shared prefixes stored once; lookup depends only on key length LL autocomplete, spell-check prefixes
class TrieNode:
__slots__ = ("children", "end_word")
def __init__(self) -> None:
self.children: dict[str, TrieNode] = {}
self.end_word: str | None = None
class Trie:
def __init__(self) -> None:
self.root = TrieNode()
def insert(self, word: str) -> None:
node = self.root
for ch in word.lower():
node = node.children.setdefault(ch, TrieNode())
node.end_word = word
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: list[str] = []
stack = [node]
while stack:
cur = stack.pop()
if cur.end_word is not None:
results.append(cur.end_word)
stack.extend(cur.children.values())
return sorted(results)
trie = Trie()
for name in products["product"]:
trie.insert(name)
print("prefix 'w':", trie.autocomplete("w"))
print("prefix 'co':", trie.autocomplete("co"))
Output
prefix 'w': ['Waterproof Rain Jacket', 'Weeknight Kitchen Cookbook', 'Wireless Earbuds']
prefix 'co': ['Cotton Bed Sheet Set']

Union-Find maintains a partition of nn elements into disjoint sets. Always combine path compression (pointing visited nodes straight to the root during find) with union by rank (attaching the shorter tree under the taller one) to guarantee O(α(n))O(\alpha(n)) amortized time per operation.

class UnionFind:
def __init__(self, n: int) -> None:
self.parent = list(range(n))
self.rank = [0] * n
self.components = n
def find(self, x: int) -> int:
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: int, b: int) -> 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
self.components -= 1
return True
uf = UnionFind(6)
for u, v in [(0, 1), (1, 2), (3, 4), (0, 2)]:
uf.union(u, v)
print("components:", uf.components)
print("connected(0, 2):", uf.find(0) == uf.find(2))
print("connected(0, 4):", uf.find(0) == uf.find(4))
Output
components: 3
connected(0, 2): True
connected(0, 4): False

KD-trees for low-dimensional nearest neighbors

Section titled “KD-trees for low-dimensional nearest neighbors”

A KD-tree splits dd-dimensional points along alternating coordinate medians. Always standardize features before building the tree so Euclidean distance is not dominated by one high-magnitude column. Above d≈20d \approx 20, most branches overlap the query sphere (“curse of dimensionality”) and approximate methods (HNSW, IVF) beat KD-trees.

cols = ["sqft", "bedrooms", "bathrooms", "distance_to_center_km"]
raw = houses[cols].to_numpy(dtype=float)
X = (raw - raw.mean(axis=0)) / raw.std(axis=0)
tree = KDTree(X)
dists, idx = tree.query(X[0], k=4)
# Verify distances against brute-force Euclidean search
brute_dists = np.sort(np.linalg.norm(X - X[0], axis=1))[:4]
print("nearest ids:", houses.iloc[idx]["house_id"].tolist())
print("distances match brute force:", np.allclose(dists, brute_dists))
print("within radius 0.25:", len(tree.query_ball_point(X[0], r=0.25)))
Output
nearest ids: ['H0001', 'H2759', 'H2384', 'H2075']
distances match brute force: True
within radius 0.25: 20

A Bloom filter maps each item through kk hash functions into an mm-bit array. If any bit is 0, the item is definitely absent (0% false negatives). If all kk bits are 1, it is probably present with approximate false-positive rate:

p≈(1−e−kn/m)k,kopt=mnln⁡2,m≈−nln⁡p(ln⁡2)2p \approx \left(1 - e^{-kn / m}\right)^k, \qquad k_{\text{opt}} = \frac{m}{n} \ln 2, \qquad m \approx -\frac{n \ln p}{(\ln 2)^2}
Structure Problem solved Exact or approximate Memory driver
Bloom filter fast membership / duplicate guard no false negatives, tunable false positives ~10 bits per item for 1% FP
HyperLogLog distinct count (COUNT DISTINCT) ~1–2% relative error a few KB for billions of items
Count-Min Sketch heavy-hitter frequency estimates overestimates only, never underestimates O(1εln⁡1δ)O(\frac{1}{\varepsilon}\ln\frac{1}{\delta}) counters
MinHash + LSH near-duplicate sets (Jaccard similarity) candidate pairs above threshold ss bb bands ×\times rr rows; P(match)=1−(1−sr)bP(\text{match}) = 1 - (1 - s^r)^b
class BloomFilter:
"""Bit-array Bloom filter using double hashing over SHA-256."""
def __init__(self, n_items: int, fp_rate: float = 0.01) -> None:
self.m = max(8, int(-n_items * math.log(fp_rate) / (math.log(2) ** 2)))
self.k = max(1, round((self.m / n_items) * math.log(2)))
self.bits = bytearray((self.m + 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") or 1
return [(h1 + i * h2) % self.m for i in range(self.k)]
def add(self, item: str) -> None:
for pos in self._positions(item):
self.bits[pos >> 3] |= 1 << (pos & 7)
def __contains__(self, item: str) -> bool:
return all((self.bits[p >> 3] >> (p & 7)) & 1 for p in self._positions(item))
bf = BloomFilter(n_items=200, fp_rate=0.01)
for pid in products["product_id"]:
bf.add(pid)
false_pos = sum(f"X{i:03d}" in bf for i in range(200))
print(f"m={bf.m} bits ({len(bf.bits)} bytes), k={bf.k}")
print(f"all inserted found: {all(pid in bf for pid in products['product_id'])}")
print(f"false positives in 200 unseen keys: {false_pos}")
Output
m=1917 bits (240 bytes), k=7
all inserted found: True
false positives in 200 unseen keys: 0
Trap Symptom Fix
measuring list.append on one resize looks O(n)O(n) instead of O(1)O(1) benchmark across nn inserts; amortized cost is O(1)O(1)
list.pop(0) or insert(0, x) in a loop quadratic slowdown on long lists use collections.deque with popleft() / appendleft()
LRU cache with dict + linear scan for oldest O(n)O(n) eviction defeats caching use OrderedDict.move_to_end + popitem(last=False) or @lru_cache
unnormalized case in a Trie "Wireless" and "wireless" split into separate branches normalize with .lower() on both insert and query
Union-Find without path compression or rank chain of depth nn, turning O(α(n))O(\alpha(n)) into O(n)O(n) use both path compression (or halving) and union by rank/size
building a KDTree on raw unscaled features sqft (thousands) swamps bathrooms (1–5) in distance standardize columns before KDTree(X)
using a KDTree on 100-D embeddings slower than brute force use brute-force matrix multiply for small nn or HNSW/FAISS for large nn
deleting from a standard Bloom filter clearing a bit causes false negatives for other keys use a counting Bloom filter or rebuild periodically
using Python’s built-in hash() in a persisted Bloom filter PYTHONHASHSEED randomizes hashes across processes use deterministic hashing (hashlib.sha256 or blake2b)