This is the lecture that tells you whether your code will finish in seconds, hours, or never.
A vocabulary — Big-O notation — for talking about how fast code is
A cheat sheet — the time complexity of the four data structures you will use 95% of the time
A discipline — pick the right structure before you start typing the loop
Why we waited until Day 9
Complexity arguments only make sense once you have written real loops
You have already used Vec, HashMap, iterators, recursion — every example today references code from earlier days
Talking about cost without intuition for what is being measured is just notation
A motivating example — counting k-mers two ways
Naïve — O(n²)
let windows:Vec<&[u8]>= seq.windows(k).collect();letmut counts =vec![0u32; windows.len()];for i in0..windows.len() {for j in0..windows.len() {if windows[i] == windows[j] { counts[i] +=1;}}}
With HashMap — O(n)
usestd::collections::HashMap;letmut counts: HashMap<&[u8],u32>=HashMap::new();for window in seq.windows(k) {*counts.entry(window).or_insert(0) +=1;}
For a 10 Mb genome at k=21:
Naïve O(n²): ~10¹⁴ operations — years
HashMap O(n): ~10⁷ operations — seconds
Why the algorithm matters more than the language: naive nested-loop comparison touches every pair of windows (an n × n grid), while the HashMap version touches each window once (a single row).
Big-O — what it means in one sentence
Big-O describes how the running time of an algorithm grows as the input size grows, ignoring constant factors.
The word for this is asymptotic [the behaviour as the input gets very large, with constants and lower-order terms dropped].
3 · n + 50 is O(n)
2 · n² + 10 · n + 7 is O(n²)
log₂(n) + 4 is O(log n)
The point is not to predict wall-clock seconds. It is to predict what happens when n doubles, or grows by a factor of a thousand.
The big-five complexities
Class
Name
What doubling the input does
O(1)
constant
nothing — fast no matter what n is
O(log n)
logarithmic
adds one step
O(n)
linear
doubles the time
O(n log n)
linearithmic
slightly more than doubles the time
O(n²)
quadratic
quadruples the time
O(n!)
factorial
intractable for n > 12
Five complexity curves on one chart. O(1) and O(log n) hug the bottom; O(n) rises gently; O(n log n) is slightly steeper; O(n²) explodes upward; O(n!) leaves the chart almost immediately.
A biology example for each
Class
Concrete example
O(1)
indexing into a Vec<u8> of bases: seq[1000]
O(log n)
binary search for a position in a sorted &[u32]
O(n)
counting GC content across a sequence
O(n log n)
sorting a list of read positions
O(n²)
all-vs-all pairwise alignment with naive recursion
O(n!)
exhaustive enumeration of multiple-sequence alignments
“I just want to iterate or look up by index” => Vec
“I want to look up by key, order does not matter” => HashMap
“I want to look up by key and iterate keys in sorted order” => BTreeMap
“I just need to test membership” => HashSet
“I need to push and pop at both ends” => VecDeque
A picture — operation costs by data structure
Cheat-sheet style table comparing Vec, HashMap, BTreeMap, HashSet across common operations.
Amortised vs worst-case
Vec::push is amortised O(1) [the average cost per operation across a long sequence, even when occasional operations are expensive]:
Most pushes write to a pre-allocated slot — O(1)
Occasionally the Vec is full — push allocates a bigger backing array and copies the old contents (O(n) for that one push)
The reallocation happens at every doubling, so it averages out to O(1)
letmut v:Vec<u8>=Vec::new();for b in seq { v.push(b);}// O(n) total for n pushes
Vec grows by doubling: the first push allocates 1 slot, the second allocates 2 more (copying the 1), the next reallocation doubles to 4, then 8, 16, …. The total copying work for n pushes adds up to ≈ 2n, so the average per-push cost stays constant.
When Big-O lies
A BTreeMap lookup is O(log n); a sorted Vec scan is O(n). For n = 100 you’d expect the tree to win. In practice the Vec often wins — because the tree pays a cache miss on every pointer hop.
Concretely, for n = 100 items:
BTreeMap lookup: 7 pointer hops × ~100 ns RAM latency + 7 comparisons
≈ 700 ns + a few ns
≈ 700 ns
Sorted Vec scan: 100 comparisons in a tight loop, all bytes already in cache
≈ 100 ns total
≈ 100 ns
Result: the “asymptotically slower” linear scan is 7× faster for small n, because cache locality dominates the pointer-chasing cost.
A BTreeMap with nodes scattered across the heap (red arrows = pointer hops, each one a potential cache miss) compared to a contiguous Vec (everything in one cache line).
Big-O is a starting point, not the last word — measure for your real input sizes and access patterns.
A chain like seq.iter().filter(|b| is_gc(b)).count() is O(n) overall — one pass, constant work per element.
Iterating a slice visits each element once — O(n).
Iterating a tree (depth-first) also visits each node once — still O(n), even though the path zig-zags.
Iteration complexity is decided by how many elements you visit, not by the shape of the data structure. A sorted Vec, a HashMap, and a tree all iterate in O(n) — the question is whether you also want them sorted, and which data structure makes the per-element cost cheaper (cache locality again).
A real bioinformatics complexity story — BLAST
A naïve all-vs-all alignment of a query against a database:
query of length q, database of length d, alignment cost O(q · d) per pair
intractable for any real database
BLAST’s trick:
Pre-build a k-mer index of the database — a HashMap<kmer, positions>
For each k-mer in the query, look up positions in the index — O(1) average
Only run the expensive alignment around the hits
The hash-table lookup turns most of the search from O(database) into O(1) — and made large-scale sequence search practical.
Conceptual BLAST: split the query into short k-mers, look up each k-mer in the database’s pre-built hash index (O(1) per lookup), then extend each match with a Smith-Waterman-style alignment around it (O(match-length²), small).
The other axis — space complexity
Same notation, different resource.
A Vec<u8> of n bases — O(n) bytes
A HashMap counting all 21-mers in a 10 Mb genome — O(n) entries
An all-vs-all alignment matrix for two sequences of length n — O(n²) cells
Sometimes memory is the binding constraint, not CPU.
// O(n^2) memory — a 10 kb x 10 kb scoring matrix is 100 million cells.letmut score =vec![vec![0i32; n +1]; n +1];
How a HashMap actually works — and why it helps memory
A HashMap<K, V> is an array of slots plus a hash function (gloss: a function that turns any key into a number — the slot index).
Both insert and get are O(1) on average — one hash computation, one indexed access.
Where it saves memory in bioinformatics: counting distinct k-mers.
A naive approach stores every k-mer occurrence:
Vec<&[u8]> // 21 bytes per k-mer × 100M windows = 2.1 GB
A HashMap stores one entry per unique k-mer:
HashMap<[u8; 21], u32> // ~unique-k-mer-count × 32 bytes
// ≈ 50M × 32 = 1.6 GB
// ... but you also lose duplicates
// and just keep counts.
For sequence data with lots of repetition, the HashMap collapses the data: the same 21-mer appearing a million times stores ONE entry, not a million. That’s why every k-mer counter (jellyfish, bbmap’s kmercountexact.sh, etc.) is built on hashing.
When you don’t have to think about it
For most bioinformatics scripts working on under ~1 GB of input, default to Vec + HashMap and do not optimise
Premature optimisation costs you readability and debugging time you will not get back
Profile first — measure where the time is going before you change anything
// Default: write the obvious thing.letmut counts: HashMap<&[u8],u32>=HashMap::new();for window in seq.windows(k) {*counts.entry(window).or_insert(0) +=1;}
Recap
Big-O describes how running time grows with the input size
Pick a data structure whose complexity matches your access pattern: Vec for indexing, HashMap for keyed lookup, BTreeMap for sorted lookup, HashSet for membership
Measure before optimising — Big-O is a guide, profilers tell you the truth