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
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 n n n
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) 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) O ( 1 ) get and put
memoize pure function calls in Python
@functools.lru_cache(maxsize=256)
O ( 1 ) O(1) O ( 1 ) average lookup
prefix search and autocomplete on strings
Trie (prefix tree)
O ( L ) O(L) O ( L ) per key of length L L L
range queries and ordered iteration
balanced BST (AVL / Red-Black) or B-tree
O ( log n ) 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) O ( α ( n )) ≈ O ( 1 ) amortized
fast k-NN or radius search in low-D numeric space
scipy.spatial.KDTree
O ( log n ) O(\log n) O ( log n ) query for d ≤ 20 d \le 20 d ≤ 20
test set membership with tiny fixed memory
Bloom filter (bit array + k k k hash functions)
O ( k ) 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 = 10 3 n = 10^3 n = 1 0 3 ops
n = 10 6 n = 10^6 n = 1 0 6 ops
Typical examples
O ( 1 ) O(1) O ( 1 )
constant
1 1 1
1 1 1
dict lookup, array index, deque.popleft()
O ( α ( n ) ) O(\alpha(n)) O ( α ( n ))
inverse Ackermann
≤ 4 \le 4 ≤ 4
≤ 4 \le 4 ≤ 4
Union-Find with compression and rank
O ( log n ) O(\log n) O ( log n )
logarithmic
≈ 10 \approx 10 ≈ 10
≈ 20 \approx 20 ≈ 20
binary search, balanced BST, heap push/pop
O ( n ) O(n) O ( n )
linear
10 3 10^3 1 0 3
10 6 10^6 1 0 6
single scan, two pointers, Quickselect average, heapify
O ( n log n ) O(n \log n) O ( n log n )
linearithmic
10 4 10^4 1 0 4
2 × 10 7 2 \times 10^7 2 × 1 0 7
Timsort (sorted), mergesort, building KD-tree
O ( n 2 ) O(n^2) O ( n 2 )
quadratic
10 6 10^6 1 0 6
10 12 10^{12} 1 0 12
nested loops, pairwise distances, 2D DP on n × n n \times n n × n
O ( n 3 ) O(n^3) O ( n 3 )
cubic
10 9 10^9 1 0 9
10 18 10^{18} 1 0 18
dense matrix multiply (n × n n \times n n × n ), Floyd–Warshall
O ( 2 n ) O(2^n) O ( 2 n )
exponential
intractable
intractable
brute-force subsets, unmemoized Fibonacci
O ( n ! ) O(n!) O ( n !)
factorial
intractable
intractable
brute-force permutations (TSP)
For divide-and-conquer recurrences T ( n ) = a T ( n / b ) + O ( n d ) T(n) = a T(n / b) + O(n^d) T ( n ) = a T ( n / b ) + O ( n d ) (Master Theorem):
Condition
Result
Example
d > log b a d > \log_b a d > log b a (work at root dominates)
T ( n ) = O ( n d ) T(n) = O(n^d) T ( n ) = O ( n d )
Quickselect average (a = 1 , b = 2 , d = 1 ⇒ O ( n ) a=1, b=2, d=1 \Rightarrow O(n) a = 1 , b = 2 , d = 1 ⇒ O ( n ) )
d = log b a d = \log_b a d = log b a (equal work per level)
T ( n ) = O ( n d log n ) T(n) = O(n^d \log n) T ( n ) = O ( n d log n )
mergesort (a = 2 , b = 2 , d = 1 ⇒ O ( n log n ) a=2, b=2, d=1 \Rightarrow O(n \log n) a = 2 , b = 2 , d = 1 ⇒ 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) a = 1 , b = 2 , d = 0 ⇒ O ( log n ) )
d < log b a d < \log_b a d < log b a (leaves dominate)
T ( n ) = O ( n log b a ) T(n) = O(n^{\log_b a}) T ( n ) = O ( n l o g b a )
Karatsuba (a = 3 , b = 2 , d = 1 ⇒ O ( n 1.585 ) a=3, b=2, d=1 \Rightarrow O(n^{1.585}) a = 3 , b = 2 , d = 1 ⇒ O ( n 1.585 ) )
Amortized scenario
Worst single op
Amortized cost
Why
dynamic array (list.append)
O ( n ) O(n) O ( n ) on resize
O ( 1 ) O(1) O ( 1 )
doubling capacity copies 1 + 2 + 4 + ⋯ + n < 2 n 1 + 2 + 4 + \dots + n < 2n 1 + 2 + 4 + ⋯ + n < 2 n items
hash table (dict / set insert)
O ( n ) O(n) O ( n ) on rehash
O ( 1 ) O(1) O ( 1 )
load factor capped (≈ 2 / 3 \approx 2/3 ≈ 2/3 in CPython); doubling spreads rehash cost
monotonic stack / sliding window
O ( n ) O(n) O ( n ) pops in one step
O ( 1 ) 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 ( log n )
O ( α ( n ) ) O(\alpha(n)) O ( α ( n ))
path compression flattens trees; rank keeps height bounded
binary heap build (heapq.heapify)
—
O ( n ) O(n) O ( n ) total
bottom-up sifting does most work on shallow subtrees
Average-case time unless marked; n n n is items, L L L is string length, k k k is hash count, d d d is dimension.
Structure
Lookup / Query
Insert
Delete
Space
Best for
list (dynamic array)
O ( 1 ) O(1) O ( 1 ) index, O ( n ) O(n) O ( n ) scan
O ( 1 ) O(1) O ( 1 ) end, O ( n ) O(n) O ( n ) front
O ( 1 ) O(1) O ( 1 ) end, O ( n ) O(n) O ( n ) front
O ( n ) O(n) O ( n )
sequences, stacks, cache-friendly scans
deque (doubly linked blocks)
O ( 1 ) O(1) O ( 1 ) ends, O ( n ) O(n) O ( n ) mid
O ( 1 ) O(1) O ( 1 ) both ends
O ( 1 ) O(1) O ( 1 ) both ends
O ( n ) O(n) O ( n )
FIFO queues, BFS, fixed windows
dict / set (hash table)
O ( 1 ) O(1) O ( 1 ) avg, O ( n ) O(n) O ( n ) worst
O ( 1 ) O(1) O ( 1 ) avg
O ( 1 ) O(1) O ( 1 ) avg
O ( n ) O(n) O ( n )
key lookup, deduplication, counting
heapq (binary min-heap)
O ( 1 ) O(1) O ( 1 ) min
O ( log n ) O(\log n) O ( log n )
O ( log n ) O(\log n) O ( log n ) min
O ( n ) O(n) O ( n )
priority queues, Dijkstra, top-k k k
Doubly linked list
O ( n ) O(n) O ( n ) by value
O ( 1 ) O(1) O ( 1 ) given node
O ( 1 ) O(1) O ( 1 ) given node
O ( n ) 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 ( log n ) O(\log n) O ( log n )
O ( 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(L) O ( L )
O ( ∑ L ) O(\sum L) O ( ∑ L )
autocomplete, prefix counts, IP routing
Union-Find (DSU)
O ( α ( n ) ) O(\alpha(n)) O ( α ( n )) find
O ( α ( n ) ) O(\alpha(n)) O ( α ( n )) union
not supported
O ( n ) O(n) O ( n )
connected components, Kruskal MST
KD-tree (low d d d )
O ( log n ) O(\log n) O ( log n ) avg, O ( n ) O(n) O ( n ) high d d d
O ( log n ) O(\log n) O ( log n ) static build O ( n log n ) O(n \log n) O ( n log n )
rebuild
O ( n ) O(n) O ( n )
spatial / low-D nearest neighbors
Bloom filter
O ( k ) O(k) O ( k )
O ( k ) O(k) O ( k )
not supported (needs counting filter)
O ( m ) 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) O ( 1 ) key lookup) with a doubly linked list (for O ( 1 ) 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.
"""Fixed-capacity LRU cache with O(1) get and put."""
def __init__ (self, capacity: int ) -> None :
self .store: OrderedDict[ str , float ] = OrderedDict()
def get (self, key: str ) -> float | None :
if key not in self .store:
self .store.move_to_end(key)
def put (self, key: str , value: float ) -> None :
self .store.move_to_end(key)
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 } " )
keys (LRU -> MRU): ['P001', 'P004', 'P002']
Tree variant
Node branching
Key property
Primary use
Binary Search Tree (BST)
2 children
left < node < right; degrades to O ( n ) O(n) O ( n ) on sorted input
teaching baseline
AVL / Red-Black tree
2 children
rotations enforce height O ( log n ) 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 L L L
autocomplete, spell-check prefixes
__slots__ = ( "children" , "end_word" )
def __init__ (self) -> None :
self .children: dict[ str , TrieNode] = {}
self .end_word: str | None = None
def __init__ (self) -> None :
def insert (self, word: str ) -> None :
node = node.children.setdefault(ch, TrieNode())
def autocomplete (self, prefix: str ) -> list[ str ]:
for ch in prefix.lower():
if ch not in node.children:
if cur.end_word is not None :
results.append(cur.end_word)
stack.extend(cur.children.values())
for name in products[ "product" ]:
print ( "prefix 'w':" , trie.autocomplete( "w" ))
print ( "prefix 'co':" , trie.autocomplete( "co" ))
prefix 'w': ['Waterproof Rain Jacket', 'Weeknight Kitchen Cookbook', 'Wireless Earbuds']
prefix 'co': ['Cotton Bed Sheet Set']
Union-Find maintains a partition of n n n 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)) O ( α ( n )) amortized time per operation.
def __init__ (self, n: int ) -> None :
self .parent = list ( range (n))
def find (self, x: int ) -> int :
while self .parent[x] != x:
self .parent[x] = self .parent[ self .parent[x]] # path halving
def union (self, a: int , b: int ) -> bool :
ra, rb = self .find(a), self .find(b)
if self .rank[ra] < self .rank[rb]:
if self .rank[ra] == self .rank[rb]:
for u, v in [( 0 , 1 ), ( 1 , 2 ), ( 3 , 4 ), ( 0 , 2 )]:
print ( "components:" , uf.components)
print ( "connected(0, 2):" , uf.find( 0 ) == uf.find( 2 ))
print ( "connected(0, 4):" , uf.find( 0 ) == uf.find( 4 ))
A KD-tree splits d d d -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 ≈ 20 d \approx 20 d ≈ 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 )
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 )))
nearest ids: ['H0001', 'H2759', 'H2384', 'H2075']
distances match brute force: True
A Bloom filter maps each item through k k k hash functions into an m m m -bit array. If any bit is 0, the item is definitely absent (0% false negatives). If all k k k bits are 1, it is probably present with approximate false-positive rate:
p ≈ ( 1 − e − k n / m ) k , k opt = m n ln 2 , m ≈ − n ln p ( ln 2 ) 2 p \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} p ≈ ( 1 − e − k n / m ) k , k opt = n m ln 2 , m ≈ − ( ln 2 ) 2 n ln p
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}) O ( ε 1 ln δ 1 ) counters
MinHash + LSH
near-duplicate sets (Jaccard similarity)
candidate pairs above threshold s s s
b b b bands × \times × r r r rows; P ( match ) = 1 − ( 1 − s r ) b P(\text{match}) = 1 - (1 - s^r)^b P ( match ) = 1 − ( 1 − s r ) b
"""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" ]:
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 } " )
m=1917 bits (240 bytes), k=7
false positives in 200 unseen keys: 0
Trap
Symptom
Fix
measuring list.append on one resize
looks O ( n ) O(n) O ( n ) instead of O ( 1 ) O(1) O ( 1 )
benchmark across n n n inserts; amortized cost is O ( 1 ) 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) 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 n n n , turning O ( α ( n ) ) O(\alpha(n)) O ( α ( n )) into O ( n ) 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 n n n or HNSW/FAISS for large n n n
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)