Algorithms and data structure speeds

Day 9, lecture 1

Rust for bioinformaticians

What this lecture is

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();
let mut counts = vec![0u32; windows.len()];
for i in 0..windows.len() {
    for j in 0..windows.len() {
        if windows[i] == windows[j] {
            counts[i] += 1;
        }
    }
}

With HashMap — O(n)

use std::collections::HashMap;

let mut 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
Left: a grid of n × n small boxes showing that the naive algorithm visits every (i, j) pair. Right: a single row of n boxes showing that the HashMap algorithm visits each window once. Annotation: same problem; n² operations versus n operations.

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
Line chart with input size n on the x-axis (log scale) and number of operations on the y-axis (log scale). Six labelled curves: O(1) flat at the bottom; O(log n) almost flat slightly above; O(n) a straight diagonal line; O(n log n) parallel to but slightly above O(n); O(n^2) much steeper; O(n!) shooting off the top of the chart.

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

Data structures the standard library gives you

Type What it is Big-O highlights
Vec<T> indexed list index O(1), push O(1) amortised, search O(n)
HashMap<K, V> hash table lookup/insert O(1) average
BTreeMap<K, V> balanced tree lookup/insert O(log n); sorted iteration free
HashSet<T> hash set membership test O(1) average
VecDeque<T> double-ended queue push/pop at either end O(1)

When to pick which

  • “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

A coloured cheat-sheet table with four rows (Vec, HashMap, BTreeMap, HashSet) and several columns for the cost of common operations (index, insert, lookup, search, sorted iteration). Cells are colour-coded by complexity class — O(1) green, O(log n) yellow, O(n) red.

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)
let mut v: Vec<u8> = Vec::new();
for b in seq { v.push(b); }    // O(n) total for n pushes
A series of Vec snapshots showing capacities 1, 2, 4, 8, 16, 32 with the cost of each reallocation labelled. Below: a summation 1 + 2 + 4 + 8 + 16 + 32 = 63 ≈ 2 × 32, showing total work is linear in n.

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.

Left panel: BTreeMap shown as 7 small node boxes scattered across a 'heap' band; red arrows trace the pointer chain from root through 7 hops to the target. Right panel: a contiguous Vec shown as a single row of 100 cells; a blue arrow scans linearly. Latency annotations: ~100 ns per cache miss vs ~1 ns per cached comparison.

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.

Iterator combinator complexities

Combinator Cost
.iter().count() O(n)
.iter().find(...) O(n) worst case
.iter().min() / .max() O(n)
.iter().sum() O(n)
.sort() on a slice O(n log n)
.dedup() on a slice O(n), needs sorted input

A chain like seq.iter().filter(|b| is_gc(b)).count() is O(n) overall — one pass, constant work per element.

A row of array cells with an arrow scanning left-to-right, one cell per step. Annotation: n cells, n steps, O(n).

Iterating a slice visits each element once — O(n).

A binary tree with 7 nodes; the DFS traversal path drawn as a numbered red arrow visiting each node in order 1-7. Annotation: same number of visits as nodes — still 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.

An SMIL-animated diagram showing: step 1, query sequence shown as boxes, then split into k-mer windows; step 2, each k-mer becomes a hash lookup arrow into the database index (a HashMap-like box); step 3, each hit triggers a small local alignment extension around the hit position. Total animation about 5 seconds.

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.
let mut 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).

       insert(k, v):
         slot = hash(k) % slots.len()
         slots[slot] = (k, v)

       get(k):
         slot = hash(k) % slots.len()
         return slots[slot]

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.
let mut 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

Where to read more