Shelves / Foundations of Computing
CS·04
Algorithms
Measuring cost with asymptotic analysis, then the core toolkit: searching, sorting, recursion, divide and conquer, dynamic programming, greedy methods, graph and string algorithms.
Start here: what algorithms are and how to compare them
An algorithm is a method
An algorithm is a finite, precise, step-by-step method that solves a problem for every valid input, not just the example you tried. A recipe that only works on Tuesdays isn't an algorithm. Three properties to check for any algorithm:
- Correctness: does it always give the right answer, including for edge cases (empty input, one item, duplicates, huge values)?
- Termination: does it always finish?
- Efficiency: how much time (steps) and space (memory) does it need as the input grows?
Usually there are several correct algorithms for one problem, and they differ enormously in efficiency. That's what this chapter is about.
A first comparison: guessing a number
I've picked a whole number between 1 and n, and I'll say "higher" or "lower" after each guess. Two strategies:
- One by one: guess 1, 2, 3… In the worst case you need n guesses.
- Halving: guess the middle; whichever answer I give rules out half of what's left; repeat. Each guess halves the range.
def binary_guesses(secret, n):
lo, hi, steps = 1, n, 0
while True:
steps += 1
mid = (lo + hi) // 2
if mid == secret: return steps
if mid < secret: lo = mid + 1 # "higher"
else: hi = mid - 1 # "lower"
n= 100: worst case one-by-one 100 guesses; halving 7 guesses
n=1,000,000: worst case one-by-one 1,000,000 guesses; halving 20 guesses
Twenty guesses for a million numbers, because 2²⁰ ≈ 1,000,000: halving a million twenty times leaves one. This is binary search, and the number of halvings is the logarithm base 2 (log₂ n), the inverse of repeated doubling. Binary search only works because the numbers are in order: it relies on "lower" ruling out everything above. Many fast algorithms work by keeping data organised so each step can discard a large part of the problem.
Measuring by counting steps
Timing a program in seconds depends on the computer, the language and what else is running. Algorithms are compared instead by counting basic steps as a function of the input size n, and asking how that count grows. Big-O notation (introduced in chapter 3) keeps only the dominant growth: 3n² + 5n + 20 steps is O(n²), because for large n the n² term swamps everything else.
How different growth rates compare as n grows:
n log2 n n n log2 n n^2 2^n
10 3.3 10 33 100 1,024
100 6.6 100 664 10,000 1.3e+30
1,000 10.0 1,000 9,966 1,000,000 1.1e+301
1,000,000 19.9 1,000,000 19,931,569 1,000,000,000,000 > 10^300000
Read the last row: at a million items, an O(log n) algorithm does about 20 steps, O(n) a million, O(n log n) about twenty million (a fraction of a second), O(n²) a trillion (minutes to hours), and O(2ⁿ) more steps than there are atoms in the universe. For large inputs, the growth rate matters far more than how fast your computer is. A smarter algorithm on a laptop beats a naive one on a supercomputer.
Searching and sorting by hand
Two problems appear everywhere, and you already know algorithms for both from daily life:
- Searching: finding a name in an unsorted pile of forms means checking each one (linear search, O(n)); finding a word in a dictionary means opening near where it should be and narrowing down (binary search, O(log n), sorted input only).
- Sorting: arranging playing cards in your hand. Picking each new card and sliding it into place among the sorted ones is insertion sort (fine for a hand of cards, O(n²) for large inputs). Splitting a big pile in half, sorting each half (the same way, recursively), then merging the two sorted halves by repeatedly taking the smaller top card is merge sort, O(n log n). The full-depth sections cover these and seven more, and why libraries use hybrids.
Recursion: a function that uses itself
A recursive function solves a problem by solving a smaller version of the same problem, until the problem is so small the answer is obvious (the base case). Factorial: 4! = 4 × 3!, 3! = 3 × 2!, and so on down to 1! = 1.
def factorial(n, depth=0):
print(" " * depth + f"factorial({n}) called")
result = 1 if n <= 1 else n * factorial(n - 1, depth + 1)
print(" " * depth + f"factorial({n}) returns {result}")
return result
factorial(4)
factorial(4) called
factorial(3) called
factorial(2) called
factorial(1) called
factorial(1) returns 1
factorial(2) returns 2
factorial(3) returns 6
factorial(4) returns 24
The indentation shows the call stack (chapter 2): each call waits, suspended, while the smaller call runs, then finishes its own multiplication when the answer comes back. Two rules make recursion work: there must be a base case that stops it, and each call must move closer to it. Break either rule and the calls never end (until the stack runs out: chapter 2's lab measures where).
Remembering answers: dynamic programming
How many ways can you climb n stairs taking 1 or 2 steps at a time? To reach stair n you came from stair n − 1 or n − 2, so ways(n) = ways(n − 1) + ways(n − 2). Written directly as recursion, it recomputes the same values again and again; remembering each answer once (memoisation) removes the waste:
def ways(n): # naive: recomputes the same subproblems repeatedly
return 1 if n <= 1 else ways(n - 1) + ways(n - 2)
memo = {}
def ways_memo(n): # remembers every answer it has computed
if n <= 1: return 1
if n not in memo: memo[n] = ways_memo(n - 1) + ways_memo(n - 2)
return memo[n]
10 stairs: 89 ways; naive recursion made 177 calls; memoised computed 9 new answers
25 stairs: 121,393 ways; naive recursion made 242,785 calls; memoised computed 24 new answers
The naive version's calls grow exponentially (each step roughly multiplies them by 1.6); the memoised version computes each stair's answer once. That is dynamic programming: when a problem breaks into overlapping subproblems, solve each once and reuse the answers. It turns many "impossible" problems into easy ones.
Greedy choices, and when they fail
A greedy algorithm makes the choice that looks best right now and never reconsiders. Making change with the fewest coins by always taking the largest coin that fits:
greedy, coins 1,2,5,10, amount 18: [10, 5, 2, 1]
greedy, coins 1,3,4, amount 6: [4, 1, 1] ← but 3+3 uses only two coins
With Indian (or most real) coin systems, greedy is optimal. With coins of 1, 3 and 4 it isn't: taking the 4 first leads to three coins where two would do. Greedy algorithms are fast and simple, and correct only when you can prove that the locally best choice is always part of a globally best answer (the full-depth section shows how such proofs go). When greedy fails, dynamic programming usually works.
Exploring a map: breadth-first search
To find the shortest route on a grid map (walls marked #), explore in rings: first every square one move away, then every square two moves away, and so on, like ripples on a pond. The first time you reach the goal, you've found a shortest path. This is breadth-first search (BFS), and it uses a queue (chapter 3) to process squares in the order they were discovered:
grid = ["S..#....",
".#.#.##.",
".#...#..",
".####.#.",
"......#G"]
dist = {start: 0}; q = deque([start])
while q:
r, c = q.popleft()
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] != "#" and (nr, nc) not in dist:
dist[(nr, nc)] = dist[(r, c)] + 1; q.append((nr, nc))
BFS: shortest path from S to G takes 15 moves; squares explored: 27
Maps, social networks ("friends of friends"), network routing and puzzle solving all use this idea. With road distances instead of single moves, the same ring-by-ring idea becomes Dijkstra's algorithm (full-depth section).
Check yourself
How deep to go in algorithms
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere and L4 in the labs at the end, which is the foundation every later volume builds on.
| Level | What you can do |
|---|---|
| L1 | Name the classic algorithms and their complexities |
| L2 | Implement and apply them correctly, using library versions where they exist |
| L3 | Prove why they work (invariants, exchange arguments, recurrences) and derive their costs |
| L4 | Find the algorithmic cause of slowness from profiles and input shapes (quadratic hiding in a loop, bad pivots, recursion depth) |
| L5 | Choose the algorithm for real constraints: input size and distribution, memory, stability, cache behaviour, constant factors |
| L6 | Keep algorithmic performance stable as data grows; set guards against adversarial inputs |
Complexity analysis
What we measure
An algorithm is a finite, precise procedure that solves a problem for every valid input. To compare algorithms independently of hardware, we count how the number of basic steps grows with the input size n. n might be the number of elements, the number of bits, or the number of vertices plus edges, depending on the problem. The textbook machine is the RAM model: memory reads, arithmetic and comparisons each cost one unit. Chapter 3 showed where that model breaks (caches), but it's the right starting point because it captures growth, and growth dominates once inputs get large.
Here is why growth matters more than constants. Suppose a machine does 10⁹ simple operations per second:
| Growth | n = 10³ | n = 10⁶ | n = 10⁹ | Largest n in ~1 second |
|---|---|---|---|---|
| O(1) | 1 ns | 1 ns | 1 ns | any |
| O(log n) | 10 ns | 20 ns | 30 ns | any |
| O(n) | 1 µs | 1 ms | 1 s | ~10⁹ |
| O(n log n) | 10 µs | 20 ms | 30 s | ~4×10⁷ |
| O(n²) | 1 ms | 17 min | 32 years | ~3×10⁴ |
| O(n³) | 1 s | 32,000 years | — | ~1,000 |
| O(2ⁿ) | 10²⁸⁰ years | — | — | ~30 |
| O(n!) | — | — | — | ~12 |
A 1000× faster computer lets an O(n) algorithm handle 1000× more data, an O(n²) one about 32× more, and an O(2ⁿ) one about 10 more elements. Better algorithms beat better hardware.
Big-O, Big-Omega and Big-Theta
These notations describe a function's growth while ignoring constant factors and small inputs. Let f(n) be the cost of your algorithm.
- f(n) = O(g(n)), an upper bound, means there exist constants c > 0 and n₀ such that f(n) ≤ c·g(n) for all n ≥ n₀. In words, f grows no faster than g.
- f(n) = Ω(g(n)), a lower bound, means f(n) ≥ c·g(n) for all n ≥ n₀. f grows at least as fast as g.
- f(n) = Θ(g(n)), a tight bound, means both: f grows exactly as fast as g, up to constants.
- Little-o: f = o(g) means f grows strictly slower (f/g → 0). For example, n = o(n²).
Worked example: f(n) = 3n² + 10n + 50.
- It's O(n²): take c = 4. Then 3n² + 10n + 50 ≤ 4n² once n² ≥ 10n + 50, which holds for n ≥ 14.
- It's also O(n³), which is true but uninformative.
- It's Θ(n²), the precise statement. When engineers say "O(n²)" in conversation they usually mean Θ.
Rules of thumb that follow from the definitions:
- Drop constant factors: 5n is O(n).
- Keep only the dominant term: n² + n log n + 1000 is O(n²).
- Logarithm bases don't matter: log₂ n = log₁₀ n / log₁₀ 2, which is a constant factor, so we just write log n.
- Sequential steps add (O(n) + O(n²) = O(n²)). Nested steps multiply (a loop of n iterations, each O(log n), is O(n log n)).
Common growth classes
| Class | Name | Typical source |
|---|---|---|
| O(1) | constant | Array index, hash lookup (average), push to a stack |
| O(log n) | logarithmic | Binary search, balanced tree operation, heap push/pop: halving the problem each step |
| O(√n) | square root | Trial-division primality test |
| O(n) | linear | One pass over the input |
| O(n log n) | linearithmic | Efficient sorting, divide-and-conquer with linear merge |
| O(n²) | quadratic | All pairs, nested loops, simple sorts |
| O(n³) | cubic | Naive matrix multiply, Floyd–Warshall |
| O(2ⁿ) | exponential | All subsets, naive recursion with two branches |
| O(n!) | factorial | All permutations (brute-force travelling salesman) |
Note the difference between polynomial time (O(n^k) for a constant k, considered "tractable") and exponential time. Whether every problem whose solution can be checked in polynomial time can also be solved in polynomial time is the famous P vs NP question. Problems like SAT, travelling salesman (decision version), graph colouring and knapsack are NP-complete: a polynomial algorithm for any one of them would give one for all. In practice you meet them as "this scheduling problem is NP-hard," which tells you to reach for heuristics, approximations, or solvers (SAT/ILP), and to stop hunting for a clever exact algorithm.
Best, average and worst case
The same algorithm can behave very differently on different inputs of the same size:
- Worst case: an upper bound over all inputs of size n. This is what guarantees are made of (latency SLOs, adversarial input).
- Average case: the expected cost over some distribution of inputs, usually uniformly random. It's realistic, but only as good as the distribution assumption.
- Best case: rarely useful, except to show an algorithm is adaptive (insertion sort is O(n) on already-sorted input).
Examples:
| Algorithm | Best | Average | Worst |
|---|---|---|---|
| Linear search | O(1) | O(n) | O(n) |
| Hash table lookup | O(1) | O(1) | O(n) (all keys collide) |
| Quicksort (fixed pivot) | O(n log n) | O(n log n) | O(n²) (sorted input with first-element pivot) |
| Insertion sort | O(n) | O(n²) | O(n²) |
| Merge sort | O(n log n) | O(n log n) | O(n log n) |
Average and expected differ subtly. Expected O(n log n) for randomised quicksort means "for every input, averaged over the algorithm's own random choices." No adversary can pick a bad input in advance. Average O(n log n) means "averaged over random inputs," and an adversary can pick a bad one.
Amortised analysis
Amortised cost is the average cost per operation over the worst-case sequence of operations. It doesn't involve probability: it guarantees the total. If n operations cost O(n) total, each is amortised O(1), even if one of them occasionally costs O(n).
There are three standard proof techniques, shown here on a dynamic array that doubles when full:
- Aggregate method: count the total and divide. n pushes cause copies of 1 + 2 + 4 + … + n/2 < n elements, plus n writes. The total is < 3n, so the amortised cost is O(1).
- Accounting (banker's) method: charge each push 3 coins. One pays for the write, and two are saved on the element. When the array doubles from capacity k to 2k, the k/2 elements pushed since the last doubling hold k saved coins, which pays to copy all k elements. The bank never goes negative.
- Potential method: define a potential Φ = 2·len − cap, the "stored energy." Amortised cost = actual cost + ΔΦ. A normal push costs 1 + 2 = 3. A doubling push copies len elements, but Φ drops by about len, so it also comes to 3.
Other amortised O(1) structures include a queue built from two stacks, union-find (inverse-Ackermann amortised), and splay trees (O(log n) amortised).
Time–space trade-offs
You can often buy time with memory or memory with time:
- Caching and memoisation: store results so you never recompute them (dynamic programming, CDN caches).
- Precomputed tables: lookup tables for CRC,
popcounton old CPUs, trigonometry in embedded systems. - Indexes: a database index uses extra disk to turn O(n) scans into O(log n) lookups, and slows writes.
- Compression: spend CPU to save memory and bandwidth.
- Bloom filters: give up exactness to save memory.
- Recomputation: deep-learning gradient checkpointing discards activations and recomputes them, trading compute for memory.
Analysing code
A practical recipe:
- Identify n, and if there are several inputs, use several variables (O(V + E), O(n·m)).
- Simple statements cost O(1).
- A loop costs (number of iterations) × (cost per iteration). Watch for loops that halve or double, which are O(log n).
- Nested loops multiply, unless the inner bound depends on the outer variable in a way that changes the sum.
for i in 0..n { for j in i..n }is n(n+1)/2, which is still O(n²). - Library calls have costs too.
list.contains(x)inside a loop is O(n) per call. Java'sString +=in a loop is O(n²) total. Goappendis amortised O(1). - Recursion: write a recurrence and solve it. T(n) = 2T(n/2) + O(n) for merge sort solves to O(n log n). Chapter 5 shows how to solve recurrences, including the master theorem.
// What's the complexity?
for (int i = 1; i < n; i *= 2) // log n iterations
for (int j = 0; j < i; j++) // i iterations: 1 + 2 + 4 + … + n/2
work();
// Total = 1 + 2 + 4 + … < 2n → O(n), not O(n log n). The inner work forms a geometric series.
Searching
Linear search
Check each element in turn until you find the target. It takes O(n), works on unsorted data and any sequence (including linked lists and streams), and for small n (under about 32 to 64 elements) it's often faster than smarter methods, because it's branch-predictable and SIMD-friendly. Compilers and standard libraries vectorise it (memchr checks 32 bytes per instruction with AVX2).
The sentinel trick removes the bounds check from the loop. Place the target at the end, so the loop is guaranteed to stop, then check whether you stopped at the sentinel.
Binary search
On sorted data, compare the target with the middle element and discard the half that can't contain it. Each step halves the range, so it takes O(log n): about 30 comparisons for a billion elements.
The hard part is getting the details right. The reliable way is to maintain an explicit loop invariant. The most useful form is the half-open lower bound: find the first index whose element is ≥ target.
/// First index i such that xs[i] >= target (xs.len() if none). Invariant:
/// everything in [0, lo) is < target, everything in [hi, len) is >= target.
fn lower_bound(xs: &[i32], target: i32) -> usize {
let (mut lo, mut hi) = (0, xs.len());
while lo < hi {
let mid = lo + (hi - lo) / 2; // no overflow
if xs[mid] < target { lo = mid + 1; } else { hi = mid; }
}
lo
}
// std: xs.binary_search(&t) -> Result<usize, usize>, xs.partition_point(|&x| x < t)
static int lowerBound(int[] a, int target) {
int lo = 0, hi = a.length; // half-open [lo, hi)
while (lo < hi) {
int mid = (lo + hi) >>> 1; // unsigned shift: safe even if lo + hi overflows
if (a[mid] < target) lo = mid + 1; else hi = mid;
}
return lo;
}
// std: Arrays.binarySearch returns (-(insertion point) - 1) when not found
func lowerBound(a []int, target int) int {
lo, hi := 0, len(a)
for lo < hi {
mid := int(uint(lo+hi) >> 1)
if a[mid] < target { lo = mid + 1 } else { hi = mid }
}
return lo
}
// std: sort.SearchInts(a, t), slices.BinarySearch(a, t) (index, found)
// The standard library gives you all variants on any sorted random-access range:
auto it = std::lower_bound(v.begin(), v.end(), t); // first >= t
auto it2 = std::upper_bound(v.begin(), v.end(), t); // first > t
bool has = std::binary_search(v.begin(), v.end(), t);
auto [first, last] = std::equal_range(v.begin(), v.end(), t); // all copies of t
size_t lower_bound(const int *a, size_t n, int target) {
size_t lo = 0, hi = n;
while (lo < hi) {
size_t mid = lo + (hi - lo) / 2;
if (a[mid] < target) lo = mid + 1; else hi = mid;
}
return lo;
}
// stdlib: bsearch() finds *an* equal element (no lower-bound semantics)
fn lowerBound(xs: []const i32, target: i32) usize {
var lo: usize = 0;
var hi: usize = xs.len;
while (lo < hi) {
const mid = lo + (hi - lo) / 2;
if (xs[mid] < target) lo = mid + 1 else hi = mid;
}
return lo;
}
// std: std.sort.lowerBound / std.sort.binarySearch (signatures change between releases)
Binary search on the answer is a powerful generalisation. Binary search works on any monotonic predicate: a yes/no question that is false, false, …, false, true, true, … over some range. "What's the minimum ship capacity that delivers all packages within D days?" Check a capacity c in O(n), and since larger capacities never hurt, binary search c. The same shape covers "minimum time," "maximum minimum distance" and similar optimisation questions, and also git bisect.
Interpolation search
Binary search always probes the middle. Interpolation search guesses where the target should be, the way you open a phone book near "S" for "Smith":
pos = lo + (target − a[lo]) × (hi − lo) / (a[hi] − a[lo])
On uniformly distributed keys this averages O(log log n) probes, which is about 5 for a billion keys. On skewed data it degrades to O(n). Real systems use the idea in learned indexes, which model the key distribution, and in exponential and galloping search (used by TimSort's merges).
Sorting
Properties of sorting algorithms
Before the algorithms, the vocabulary used to compare them:
- Comparison sort: it only learns about elements by comparing pairs (
a < b). Such sorts need Ω(n log n) comparisons in the worst case. The proof: there are n! possible orderings, each comparison has 2 outcomes, so a decision tree that distinguishes all n! needs height ≥ log₂(n!) ≈ n log₂ n − 1.44n. - Non-comparison sort (counting, radix, bucket): it exploits key structure such as small integers or fixed-width digits to beat n log n.
- Stable: equal keys keep their original relative order. This matters when you sort by multiple keys in passes. Sort by name, then stably by department, and names stay alphabetical within each department. It also matters for user-visible ordering.
- In-place: it uses O(1) or O(log n) extra memory, as opposed to O(n).
- Adaptive: it runs faster on partially sorted input. Real-world data often contains sorted runs.
- Online: it can sort elements as they arrive.
| Algorithm | Best | Average | Worst | Extra space | Stable | Notes |
|---|---|---|---|---|---|---|
| Insertion | n | n² | n² | 1 | ✓ | Fastest for tiny or nearly sorted inputs |
| Selection | n² | n² | n² | 1 | ✗ | Minimum number of swaps (n − 1) |
| Bubble | n | n² | n² | 1 | ✓ | Teaching only |
| Merge | n log n | n log n | n log n | n | ✓ | Predictable; external sorting; linked lists |
| Quick | n log n | n log n | n² | log n | ✗ | Fastest general in-memory sort in practice |
| Heap | n log n | n log n | n log n | 1 | ✗ | Guaranteed bound, in place; poor locality |
| Counting | n + k | n + k | n + k | n + k | ✓ | Small integer keys in range k |
| Radix (LSD) | d(n + b) | d(n + b) | d(n + b) | n + b | ✓ | d digits in base b |
| Bucket | n | n + k | n² | n + k | ✓* | Uniform real numbers in a range |
Insertion sort
Grow a sorted prefix one element at a time. Take the next element and shift larger elements right until its slot appears, like sorting a hand of cards.
void insertion_sort(int *a, size_t n) {
for (size_t i = 1; i < n; i++) {
int key = a[i];
size_t j = i;
while (j > 0 && a[j - 1] > key) { a[j] = a[j - 1]; j--; } // shift right
a[j] = key;
}
}
Its cost is O(n + inversions), where an inversion is a pair that's out of order. So it's O(n) on sorted input, fast on nearly sorted input, and has tiny constants. That's why every serious hybrid sort uses insertion sort for small subarrays (below roughly 16–32 elements): introsort, TimSort, pdqsort and driftsort all do.
Selection sort
Repeatedly find the minimum of the unsorted suffix and swap it into place. It always takes Θ(n²) comparisons, but only n − 1 swaps. That's useful only when writes are very expensive (flash memory wear, for example). It isn't stable, because the long-distance swap can jump an element over an equal one.
Bubble sort
Repeatedly walk the array, swapping adjacent out-of-order pairs. After pass k, the k largest elements are in place. With an early-exit flag (stop if a pass made no swaps) it's O(n) on sorted input. Otherwise it's Θ(n²) with more swaps than insertion sort. Its value is in teaching the idea of invariants per pass. Don't use it in practice.
Merge sort
Divide the array in half, sort each half recursively, then merge the two sorted halves by repeatedly taking the smaller front element. The merge is linear, so T(n) = 2T(n/2) + O(n) = O(n log n) in every case.
func MergeSort(a []int) []int {
if len(a) <= 1 {
return a
}
mid := len(a) / 2
l, r := MergeSort(a[:mid]), MergeSort(a[mid:])
out := make([]int, 0, len(a))
i, j := 0, 0
for i < len(l) && j < len(r) {
if l[i] <= r[j] { // <= keeps it stable: ties take from the left
out = append(out, l[i]); i++
} else {
out = append(out, r[j]); j++
}
}
out = append(out, l[i:]...)
return append(out, r[j:]...)
}
fn merge_sort<T: Ord + Clone>(v: &mut [T]) {
let n = v.len();
if n <= 1 { return; }
let mid = n / 2;
merge_sort(&mut v[..mid]);
merge_sort(&mut v[mid..]);
let mut merged = Vec::with_capacity(n);
let (mut i, mut j) = (0, mid);
while i < mid && j < n {
if v[i] <= v[j] { merged.push(v[i].clone()); i += 1; }
else { merged.push(v[j].clone()); j += 1; }
}
merged.extend_from_slice(&v[i..mid]);
merged.extend_from_slice(&v[j..n]);
v.clone_from_slice(&merged);
}
static void mergeSort(int[] a, int[] tmp, int lo, int hi) { // sorts a[lo, hi)
if (hi - lo <= 1) return;
int mid = (lo + hi) >>> 1;
mergeSort(a, tmp, lo, mid);
mergeSort(a, tmp, mid, hi);
if (a[mid - 1] <= a[mid]) return; // already in order: adaptive shortcut
System.arraycopy(a, lo, tmp, lo, hi - lo);
for (int k = lo, i = lo, j = mid; k < hi; k++) {
if (i < mid && (j >= hi || tmp[i] <= tmp[j])) a[k] = tmp[i++];
else a[k] = tmp[j++];
}
}
Merge sort's strengths are its guaranteed bound, stability, sequential access (good for disks and linked lists, where merging only relinks nodes, so no extra memory is needed), and external sorting. To sort 1 TB with 16 GB of RAM: sort 16 GB chunks in memory, write them out as runs, then do a k-way merge of the runs with a heap. Databases' ORDER BY spills to disk exactly this way. Its weakness is the O(n) extra buffer.
Quicksort
Pick a pivot, partition the array so smaller elements go left and larger go right, and the pivot lands in its final position. Then recurse on both sides. There is no merge step, because the work happens before recursing.
Partition schemes:
- Lomuto: one index scans while another marks the boundary of the "< pivot" region. It's simple, does more swaps, and degrades on many duplicates.
- Hoare: two indices move inward from both ends and swap misplaced pairs. It does about three times fewer swaps and is the original 1961 scheme.
- Three-way (Dutch national flag): partition into < pivot, = pivot and > pivot. Inputs with many duplicates become linear.
static void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; }
// Hoare partition: returns j such that a[lo..j] <= pivot <= a[j+1..hi]
static long partition(int *a, long lo, long hi) {
int pivot = a[lo + (hi - lo) / 2];
long i = lo - 1, j = hi + 1;
for (;;) {
do i++; while (a[i] < pivot);
do j--; while (a[j] > pivot);
if (i >= j) return j;
swap(&a[i], &a[j]);
}
}
void quicksort(int *a, long lo, long hi) { // sorts a[lo..hi] inclusive
while (lo < hi) {
long p = partition(a, lo, hi);
if (p - lo < hi - p) { quicksort(a, lo, p); lo = p + 1; } // recurse on the smaller side,
else { quicksort(a, p + 1, hi); hi = p; } // loop on the larger: O(log n) stack
}
}
Analysis. A good pivot splits roughly in half, giving O(n log n). Always picking the smallest element (for example, the first element of already-sorted input) gives T(n) = T(n−1) + O(n) = O(n²), and with naive recursion a stack overflow too. Defences:
- Median-of-three (first, middle, last) or a random pivot. Random makes the expected time O(n log n) for every input.
- Recurse on the smaller side and loop on the larger, as in the code above, which bounds the stack at O(log n).
- Introsort (Musser, 1997): run quicksort, but if recursion depth exceeds about 2 log n, switch to heapsort. That guarantees O(n log n) worst case. This is C++
std::sort. - pdqsort (pattern-defeating quicksort, Orson Peters): introsort plus detection of sorted, reverse-sorted and many-duplicates patterns. Rust's
sort_unstableand Go'ssort/slices.Sortdescend from it.
Why is quicksort usually the fastest in practice despite its worst case? It sorts in place, its partition loop scans memory sequentially (cache-friendly), and its inner loop is tiny.
Heapsort
Build a max-heap in place (O(n), chapter 3), then repeatedly swap the root (the maximum) to the end of the array and sift down the new root over the shrinking heap. It runs in O(n log n) worst case with O(1) extra memory, which is a rare combination. It is slower in practice than quicksort, because sift-down jumps around the array (poor locality) and branches unpredictably. Its role today is as introsort's safety net and in memory-constrained systems such as the Linux kernel's sort().
fn heapsort<T: Ord>(v: &mut [T]) {
fn sift_down<T: Ord>(v: &mut [T], mut i: usize, end: usize) {
loop {
let (l, r) = (2 * i + 1, 2 * i + 2);
let mut m = i;
if l < end && v[l] > v[m] { m = l; }
if r < end && v[r] > v[m] { m = r; }
if m == i { return; }
v.swap(i, m);
i = m;
}
}
let n = v.len();
for i in (0..n / 2).rev() { sift_down(v, i, n); } // heapify: O(n)
for end in (1..n).rev() {
v.swap(0, end); // move max to its final place
sift_down(v, 0, end);
}
}
Counting sort
When keys are integers in a small range [0, k), count how many of each value occur, compute prefix sums so that count[v] is where value v's run starts, then place each element. That's O(n + k) time and O(n + k) space, with no comparisons at all. Iterating the input backward when placing (or forward, with starting offsets) makes it stable, which radix sort relies on.
func CountingSort(a []int, k int) []int { // values in [0, k)
count := make([]int, k+1)
for _, v := range a { count[v+1]++ }
for i := 1; i <= k; i++ { count[i] += count[i-1] } // count[v] = start index of value v
out := make([]int, len(a))
for _, v := range a { out[count[v]] = v; count[v]++ } // forward pass, stable
return out
}
Radix sort
Sort by one digit at a time using a stable sort per digit, usually counting sort. LSD (least-significant digit first) radix sort on 32-bit integers with base 256 needs 4 passes of counting sort over 256 buckets: O(4 · (n + 256)), which is linear in n. Stability is essential: after sorting by digit d, ties keep the order established by digits d−1 … 0.
input: 170 45 75 90 802 24 2 66
by 1s: 170 90 802 2 24 45 75 66
by 10s: 802 2 24 45 66 170 75 90
by 100s: 2 24 45 66 75 90 170 802 ✓
MSD radix sort works from the most significant digit, recursing into buckets. It suits strings and can stop early. Radix sort beats comparison sorts for large arrays of fixed-width keys. GPUs sort this way, and databases use it for integer keys. Signed integers and floats need a bit transform first (flip the sign bit; for floats, flip all bits when negative, as chapter 6 explains).
Bucket sort
For values spread roughly uniformly over a range, scatter them into n buckets by value, sort each small bucket (with insertion sort), then concatenate. The expected time is O(n) when the distribution is uniform, and O(n²) if everything lands in one bucket. Sample sort, the parallel and distributed version, picks bucket boundaries from a random sample of the data. It's how distributed systems (Spark's sortBy, TeraSort) sort across machines: each machine ends up with one key range.
What standard libraries actually use
Library sorts are carefully engineered hybrids. Know which one you're calling, because stability and worst-case behaviour differ:
| Call | Algorithm | Stable? |
|---|---|---|
C qsort |
Implementation-defined (glibc historically used merge sort when memory allowed, with a quicksort fallback; newer versions use introsort) | No guarantee |
C++ std::sort |
Introsort (quicksort + heapsort + insertion sort) | No |
C++ std::stable_sort |
Merge sort (adaptive buffer) | Yes |
Java Arrays.sort(int[]) and other primitives |
Dual-pivot quicksort (Yaroslavskiy), plus heapsort fallback in modern JDKs | N/A (primitives) |
Java Arrays.sort(Object[]), List.sort, Collections.sort |
TimSort | Yes |
Rust slice::sort |
driftsort (since 1.81; TimSort-like before) | Yes |
Rust slice::sort_unstable |
ipnsort (pdqsort lineage) | No |
Go sort.Sort, slices.Sort |
pdqsort (since Go 1.19) | No |
Go sort.Stable, slices.SortStableFunc |
Insertion sort blocks + SymMerge | Yes |
Zig std.mem.sort / std.mem.sortUnstable |
Block sort (in-place stable merge) / pdqsort | Yes / No |
Python sorted |
TimSort (Powersort merge policy since 3.11) | Yes |
TimSort (Tim Peters, 2002) finds existing ascending or descending runs, extends short runs with insertion sort to a minimum length (32–64), and merges runs with a stack discipline plus galloping (exponential search) when one run keeps "winning." On real-world data with partial order it's often close to O(n). Why do Java and Python use a stable merge-based sort for objects but quicksort for primitives? For objects, stability is observable and comparisons are expensive (compareTo calls), so TimSort's fewer comparisons win. For primitives, equal values are indistinguishable, so stability is irrelevant and raw speed wins.
Sorting in practice: cache and parallelism
At scale, memory behaviour dominates comparison counts. Quicksort and pdqsort partition sequentially. Merge sort streams. Heapsort jumps around. Branchless partitioning (BlockQuicksort) avoids mispredictions, because random data makes if (a[i] < pivot) a coin flip for the branch predictor. For huge arrays, parallel sorts split the work across cores: Java Arrays.parallelSort (fork/join merge), Rust rayon's par_sort, and C++17 std::sort(std::execution::par, …).
Recursion as an algorithmic tool
Recursion trees
Chapter 2 covered how recursion executes. Algorithmically, the key tool is the recursion tree: draw each call as a node, its sub-calls as children, and write the non-recursive work at each node. The total cost is the sum over all nodes.
Naive Fibonacci shows why this matters:
fib(n) = fib(n-1) + fib(n-2)
fib(5)
/ \
fib(4) fib(3)
/ \ / \
fib(3) fib(2) fib(2) fib(1)
/ \ / \ / \
fib(2) fib(1) … … … …
The tree has about φⁿ ≈ 1.618ⁿ nodes, so fib(50) makes about 20 billion calls. But there are only n distinct subproblems: fib(3) is computed twice, fib(2) three times, and so on. Repeated subproblems in a recursion tree are the signal for memoisation and dynamic programming.
Recursion trees also explain divide-and-conquer costs. Merge sort's tree has log n levels and each level does O(n) total merging, so the total is O(n log n).
Memoisation
Memoisation caches each subproblem's answer the first time it's computed and returns the cached value on later calls. It turns the exponential tree into a linear chain of distinct calls.
use std::collections::HashMap;
fn fib(n: u64, memo: &mut HashMap<u64, u64>) -> u64 {
if n < 2 { return n; }
if let Some(&v) = memo.get(&n) { return v; }
let v = fib(n - 1, memo) + fib(n - 2, memo);
memo.insert(n, v);
v
}
// fib(90, &mut HashMap::new()) is instant; without the memo it would take centuries.
static long[] memo = new long[100];
static long fib(int n) {
if (n < 2) return n;
if (memo[n] != 0) return memo[n];
return memo[n] = fib(n - 1) + fib(n - 2);
}
// For general keys: Map<Key, V> cache; cache.computeIfAbsent(k, …) — but NOT recursively
// on HashMap (it throws ConcurrentModificationException since Java 9).
func fib(n int, memo map[int]int) int {
if n < 2 {
return n
}
if v, ok := memo[n]; ok {
return v
}
memo[n] = fib(n-1, memo) + fib(n-2, memo)
return memo[n]
}
#include <unordered_map>
std::unordered_map<int, long long> memo;
long long fib(int n) {
if (n < 2) return n;
if (auto it = memo.find(n); it != memo.end()) return it->second;
return memo[n] = fib(n - 1) + fib(n - 2);
}
Memoisation requires pure functions: the result must depend only on the arguments. Python's @functools.cache is the one-line version.
Tail recursion and stack depth in algorithms
Algorithms written recursively inherit the stack limits from chapter 2. Rough guidance:
- Depth O(log n) (balanced divide and conquer, binary search, quicksort recursing on the smaller side) is always safe.
- Depth O(n) (DFS on a path-like graph, naive linked-list recursion, unbalanced trees) will overflow somewhere around 10⁴ to 10⁶ frames depending on frame size and language. Convert it to an explicit stack, or iterate.
- Tail-recursive formulations (accumulators) are easy to convert to loops by hand. That's the reliable way in all six languages, since none guarantees TCO except Zig's
@call(.always_tail, …)and Clang'smusttail.
Divide and conquer
The pattern
Divide and conquer solves a problem in three steps:
- Divide it into smaller subproblems of the same kind.
- Conquer each subproblem recursively, solving tiny ones directly.
- Combine the sub-answers.
The cost obeys a recurrence of the form T(n) = a·T(n/b) + f(n): a subproblems, each of size n/b, plus f(n) work to divide and combine. The master theorem (proved in chapter 5) solves most such recurrences by comparing f(n) with n^(log_b a):
| Case | Condition | Result | Example |
|---|---|---|---|
| 1. Leaves dominate | f(n) = O(n^(log_b a − ε)) | T(n) = Θ(n^(log_b a)) | Karatsuba: T = 3T(n/2) + n → Θ(n^1.585) |
| 2. Balanced | f(n) = Θ(n^(log_b a)) | T(n) = Θ(n^(log_b a) · log n) | Merge sort: 2T(n/2) + n → Θ(n log n); binary search: T(n/2) + 1 → Θ(log n) |
| 3. Root dominates | f(n) = Ω(n^(log_b a + ε)), plus a regularity condition | T(n) = Θ(f(n)) | T = 2T(n/2) + n² → Θ(n²) |
Classic divide-and-conquer algorithms
- Merge sort and quicksort: split, sort, combine (merge sort) or partition first (quicksort).
- Binary search: one subproblem, so T(n) = T(n/2) + O(1).
- Quickselect: find the k-th smallest element in expected O(n). Partition like quicksort, but recurse only into the side containing position k, so T(n) = T(n/2) + O(n) = O(n). C++
std::nth_element, Rustselect_nth_unstable, and median and percentile computations use it. Median of medians makes it worst-case O(n). - Fast exponentiation: xⁿ = (x^(n/2))², which takes O(log n) multiplications. It's the basis of modular exponentiation in RSA and of matrix-power Fibonacci in O(log n).
- Karatsuba multiplication: multiply two n-digit numbers with 3 half-size multiplications instead of 4, giving O(n^1.585). Big-integer libraries (Java
BigInteger, GMP) switch to it, and to Toom–Cook and FFT-based methods, above size thresholds. - Strassen matrix multiplication: 7 sub-multiplications instead of 8, giving O(n^2.807).
- Closest pair of points: O(n log n) by splitting at the median x coordinate and checking a narrow strip.
- Fast Fourier Transform: O(n log n) polynomial multiplication and signal processing.
// Fast modular exponentiation: (base^exp) mod m in O(log exp)
func PowMod(base, exp, m uint64) uint64 {
result := uint64(1)
base %= m
for exp > 0 {
if exp&1 == 1 {
result = mulmod(result, base, m)
}
base = mulmod(base, base, m)
exp >>= 1
}
return result
}
func mulmod(a, b, m uint64) uint64 { // avoid overflow with 128-bit multiply
hi, lo := bits.Mul64(a, b)
_, rem := bits.Div64(hi%m, lo, m)
return rem
}
Computational decomposition
Divide and conquer is also the template for parallel and distributed computation: independent subproblems can run on different cores or machines.
- Fork/join: Java's
ForkJoinPoolandRecursiveTask, Rust'srayon::join, and Go goroutines with async.WaitGroupall split work recursively until pieces are small, then combine. Work stealing keeps cores busy. - MapReduce (Google, 2004) and its descendants (Hadoop, Spark): map processes partitions independently, a shuffle groups intermediate results by key, and reduce combines each group. Word count, inverted indexes and joins over petabytes all follow this pattern.
- Associativity is the key property. If the combine step is associative (sum, max, merge of sorted runs, set union), the work can be split arbitrarily and combined in any tree shape. That's the same requirement as segment trees and parallel reductions.
// rayon: parallel divide and conquer with one call
use rayon::prelude::*;
let total: u64 = (1..=1_000_000_000u64).into_par_iter().map(|x| x % 7).sum();
// rayon splits the range recursively and work-steals across all cores
Dynamic programming
Overlapping subproblems and optimal substructure
Dynamic programming (DP) applies to problems with two properties:
- Optimal substructure: an optimal solution is built from optimal solutions to subproblems. The shortest path A→C through B consists of a shortest A→B and a shortest B→C.
- Overlapping subproblems: the same subproblems recur many times. Divide and conquer has independent subproblems, which is the difference.
DP solves each distinct subproblem once and stores the answer. The name is historical. Richard Bellman chose "dynamic programming" in the 1950s partly because it sounded impressive to funders; "programming" meant planning, as in a TV programme.
Top-down versus bottom-up
There are two ways to implement the same DP:
- Top-down (memoised recursion): write the natural recursive solution and add a cache. It computes only the subproblems actually needed, and the code mirrors the recurrence. It uses recursion depth, and hash-map caches have overhead.
- Bottom-up (tabulation): fill a table in an order where every dependency is already computed. There's no recursion, it runs fast with array access, and you can often shrink the table to O(1) or O(row) memory. You must work out the fill order yourself.
// Bottom-up Fibonacci, keeping only the last two values: O(n) time, O(1) space
fn fib(n: u64) -> u64 {
let (mut a, mut b) = (0u64, 1u64);
for _ in 0..n { (a, b) = (b, a + b); }
a
}
static long fib(int n) {
long a = 0, b = 1;
for (int i = 0; i < n; i++) { long t = a + b; a = b; b = t; }
return a;
}
Designing the state
The hardest step in DP is choosing the state: the minimal information that captures "where we are" so that the rest of the problem depends only on it. Ask yourself:
- What decisions does a solution make? Take or skip an item, which character to match, where to cut.
- What do I need to know about past decisions to make future ones optimally? Only that goes in the state. In knapsack you need "items considered so far" and "capacity left," but not which items were taken.
- How many states are there? Time ≈ (number of states) × (work per transition).
Typical state shapes:
| Shape | State | Examples |
|---|---|---|
| Prefix | dp[i] = answer for the first i elements |
Climbing stairs, house robber, LIS, word break |
| Two prefixes | dp[i][j] = answer for prefixes of two strings |
LCS, edit distance, regex matching |
| Prefix + resource | dp[i][w] = best using items < i with capacity w |
0/1 knapsack, coin change |
| Interval | dp[l][r] = answer for the subarray l..r |
Matrix-chain order, palindrome partitioning, burst balloons |
| Subset (bitmask) | dp[mask][v] = best visiting set mask, ending at v |
Travelling salesman in O(2ⁿ·n²) for n ≤ ~20 |
| Tree | dp[node][state] computed from children |
Max independent set on a tree |
| Digit | dp[pos][tight][…] |
Count numbers ≤ N with a digit property |
Designing transitions
The transition (recurrence) expresses a state in terms of smaller states, by considering the last decision:
Coin change (minimum coins to make amount A from denominations):
dp[0] = 0
dp[a] = 1 + min over coins c ≤ a of dp[a − c] ("the last coin used was c")
Edit distance (Levenshtein: minimum inserts, deletes and substitutions to turn s into t):
dp[i][0] = i, dp[0][j] = j
dp[i][j] = dp[i−1][j−1] if s[i−1] == t[j−1]
= 1 + min( dp[i−1][j], delete s[i−1]
dp[i][j−1], insert t[j−1]
dp[i−1][j−1] ) substitute
fn edit_distance(s: &str, t: &str) -> usize {
let (s, t): (Vec<char>, Vec<char>) = (s.chars().collect(), t.chars().collect());
let mut prev: Vec<usize> = (0..=t.len()).collect(); // row i-1
let mut cur = vec![0; t.len() + 1]; // row i: O(|t|) memory
for i in 1..=s.len() {
cur[0] = i;
for j in 1..=t.len() {
cur[j] = if s[i - 1] == t[j - 1] {
prev[j - 1]
} else {
1 + prev[j].min(cur[j - 1]).min(prev[j - 1])
};
}
std::mem::swap(&mut prev, &mut cur);
}
prev[t.len()]
}
// edit_distance("kitten", "sitting") == 3
func CoinChange(coins []int, amount int) int {
const inf = math.MaxInt32
dp := make([]int, amount+1)
for a := 1; a <= amount; a++ {
dp[a] = inf
for _, c := range coins {
if c <= a && dp[a-c] != inf && dp[a-c]+1 < dp[a] {
dp[a] = dp[a-c] + 1
}
}
}
if dp[amount] == inf { return -1 }
return dp[amount]
}
// CoinChange([]int{1, 5, 6, 9}, 11) == 2 (5 + 6) — greedy would pick 9+1+1 = 3 coins
// 0/1 knapsack: maximise value within capacity W, each item used at most once.
// dp[w] = best value with capacity w using items seen so far.
static int knapsack(int[] weight, int[] value, int W) {
int[] dp = new int[W + 1];
for (int i = 0; i < weight.length; i++)
for (int w = W; w >= weight[i]; w--) // iterate DOWN so each item is used once
dp[w] = Math.max(dp[w], dp[w - weight[i]] + value[i]);
return dp[W];
}
// Iterating w upward instead would allow reusing item i: the *unbounded* knapsack.
// Longest increasing subsequence in O(n log n) with "patience sorting":
// tails[k] = smallest possible tail of an increasing subsequence of length k+1.
int lis(const std::vector<int>& a) {
std::vector<int> tails;
for (int x : a) {
auto it = std::lower_bound(tails.begin(), tails.end(), x);
if (it == tails.end()) tails.push_back(x); else *it = x;
}
return tails.size();
}
// The O(n²) DP: dp[i] = 1 + max(dp[j] for j < i with a[j] < a[i]).
Reconstruction and space optimisation
DP tables give the optimal value. To recover the solution itself (which coins, which edit operations, which subsequence), either store the choice made at each state (a "parent" table), or walk the full table backward from the answer, re-deciding which transition produced each value. Walking backward needs the full table, so there's a tension with space optimisation. Hirschberg's algorithm recovers an LCS alignment in linear space with divide and conquer, and genome alignment tools use it.
Rolling arrays: when row i depends only on row i−1, keep two rows (or one, filled in the right direction, as in the knapsack loop). That takes memory from O(n·m) to O(m).
Greedy algorithms
Local versus global optimum
A greedy algorithm builds a solution one step at a time, always making the choice that looks best right now, and never reconsiders. It's simple and fast, and it's correct only for problems with the greedy-choice property: some optimal solution starts with the greedy choice, and the remaining subproblem is again of the same kind.
The coin-change counterexample shows the danger. With coins {1, 5, 6, 9} and amount 11, greedy takes 9, then 1, then 1, using 3 coins. The optimum is 5 + 6, using 2 coins. With "canonical" coin systems like {1, 2, 5, 10, 20, 50, 100}, greedy happens to be optimal. With arbitrary ones it isn't. A locally optimal step doesn't guarantee a globally optimal solution. You must prove the greedy works, or use DP.
Exchange arguments
The standard proof technique is the exchange argument: take any optimal solution that differs from the greedy one, and show you can swap in the greedy choice without making it worse. Repeating the swap transforms the optimal solution into the greedy one, so the greedy solution is optimal too.
Interval scheduling (pick the maximum number of non-overlapping meetings) shows the method. Greedy: sort by end time and repeatedly take the meeting that ends earliest among those compatible with what you've taken.
Proof by exchange. Let O be an optimal schedule, and let g be the meeting with the earliest end time. Suppose O's first meeting is o₁ ≠ g. Since g ends no later than o₁, replacing o₁ with g in O can't create a conflict with o₂ onward, and O' = O − {o₁} + {g} has the same size, so it's also optimal. Now apply the same argument to the remaining meetings, all of which start after g ends. ∎
Note that sorting by start time or by shortest duration both fail. Try to construct counterexamples: it's good practice.
# Interval scheduling: Python for brevity — the logic is identical in any language
def max_meetings(intervals):
count, last_end = 0, float("-inf")
for start, end in sorted(intervals, key=lambda iv: iv[1]): # by END time
if start >= last_end:
count += 1
last_end = end
return count
Classic greedy algorithms
| Problem | Greedy rule | Why it works |
|---|---|---|
| Interval scheduling | Earliest finish time | Exchange argument (above) |
| Fractional knapsack | Highest value/weight ratio first | Items are divisible; exchange argument. (The 0/1 version needs DP.) |
| Huffman coding | Repeatedly merge the two least-frequent symbols | Optimal prefix code; the two rarest symbols can be deepest siblings |
| Minimum spanning tree | Kruskal: cheapest edge without a cycle. Prim: cheapest edge leaving the tree | Cut property: the lightest edge across any cut is in some MST |
| Dijkstra's shortest paths | Settle the closest unsettled vertex | Non-negative weights mean no later path can be shorter |
| Job sequencing with deadlines | Earliest deadline first | Minimises maximum lateness |
| Gas station / jump game | Track the farthest reachable point | Invariant argument |
Huffman coding is a greedy algorithm you use daily. DEFLATE (used by gzip, zip and PNG), JPEG and HTTP/2's HPACK all use Huffman codes. Frequent symbols get short bit codes and rare ones get long codes, and no code is a prefix of another, so decoding is unambiguous.
freq: a:45 b:13 c:12 d:16 e:9 f:5
merge f(5)+e(9)=14 → c(12)+b(13)=25 → 14+d(16)=30 → 25+30=55 → a(45)+55=100
codes: a=0 c=100 b=101 f=1100 e=1101 d=111 (average 2.24 bits vs 3 for fixed-width)
Graph algorithms
Breadth-first search
BFS explores a graph in layers: first the start vertex, then all its neighbours, then all their unvisited neighbours, and so on. It uses a queue. In an unweighted graph, BFS discovers each vertex along a shortest path in edge count, because a vertex at distance d is always dequeued before any vertex at distance d+1. It takes O(V + E) time, since every vertex is enqueued once and every edge is examined once (twice if undirected).
// Shortest path lengths (in edges) from src in an unweighted graph
func BFS(adj [][]int, src int) []int {
dist := make([]int, len(adj))
for i := range dist { dist[i] = -1 }
dist[src] = 0
queue := []int{src}
for len(queue) > 0 {
u := queue[0]
queue = queue[1:]
for _, v := range adj[u] {
if dist[v] == -1 { // mark visited when ENQUEUED, not when dequeued
dist[v] = dist[u] + 1
queue = append(queue, v)
}
}
}
return dist
}
use std::collections::VecDeque;
fn bfs(adj: &[Vec<usize>], src: usize) -> Vec<Option<usize>> {
let mut dist = vec![None; adj.len()];
dist[src] = Some(0);
let mut q = VecDeque::from([src]);
while let Some(u) = q.pop_front() {
let du = dist[u].unwrap();
for &v in &adj[u] {
if dist[v].is_none() {
dist[v] = Some(du + 1);
q.push_back(v);
}
}
}
dist
}
static int[] bfs(List<List<Integer>> adj, int src) {
int[] dist = new int[adj.size()];
Arrays.fill(dist, -1);
dist[src] = 0;
ArrayDeque<Integer> q = new ArrayDeque<>();
q.add(src);
while (!q.isEmpty()) {
int u = q.poll();
for (int v : adj.get(u))
if (dist[v] == -1) { dist[v] = dist[u] + 1; q.add(v); }
}
return dist;
}
Marking a vertex visited when it's enqueued (not when it's dequeued) prevents it from being added to the queue many times. On grids, BFS from a cell finds the shortest maze path. Multi-source BFS (enqueue all sources at distance 0) computes distance to the nearest source: "how far is each cell from the nearest exit?" 0-1 BFS uses a deque to handle edges of weight 0 or 1 in O(V + E). BFS is also how web crawlers, garbage collectors (Cheney's copying collector is literally a BFS) and social "degrees of separation" features work.
Depth-first search
DFS goes as deep as possible along each branch before backtracking. It uses a stack, either the call stack (recursion) or an explicit one, and also takes O(V + E). It doesn't find shortest paths, but its structure is very informative. DFS assigns each vertex a discovery time and a finish time, and classifies every edge in a directed graph:
- Tree edge: leads to a newly discovered vertex.
- Back edge: leads to an ancestor that is still on the stack. A back edge means a cycle.
- Forward edge: leads to an already-finished descendant.
- Cross edge: leads to a vertex in another, finished subtree.
Uses: cycle detection, topological sort, strongly connected components, connected components, articulation points and bridges (single points of failure in a network), maze generation, solving puzzles by backtracking (sudoku, N-queens), and dependency resolution.
// Iterative DFS with an explicit stack: safe for deep graphs
fn dfs_order(adj: &[Vec<usize>], src: usize) -> Vec<usize> {
let mut seen = vec![false; adj.len()];
let mut stack = vec![src];
let mut order = Vec::new();
while let Some(u) = stack.pop() {
if seen[u] { continue; }
seen[u] = true;
order.push(u);
for &v in adj[u].iter().rev() { // reverse to visit neighbours in listed order
if !seen[v] { stack.push(v); }
}
}
order
}
Cycle detection
- Undirected graph: during DFS, an edge to an already-visited vertex that isn't your parent means a cycle. Alternatively, process edges with union-find: if both endpoints already share a root, adding the edge closes a cycle. That's exactly the check Kruskal's algorithm uses.
- Directed graph: colour vertices white (unvisited), grey (on the current DFS path) and black (finished). An edge to a grey vertex is a back edge, which means a cycle. An edge to a black vertex is fine, because it's just a cross or forward edge. Using only a visited flag in directed graphs gives false positives (diamond-shaped DAGs).
// Directed cycle detection with three colours
static boolean hasCycle(List<List<Integer>> adj) {
int[] color = new int[adj.size()]; // 0 white, 1 grey, 2 black
for (int s = 0; s < adj.size(); s++)
if (color[s] == 0 && dfs(adj, s, color)) return true;
return false;
}
static boolean dfs(List<List<Integer>> adj, int u, int[] color) {
color[u] = 1;
for (int v : adj.get(u)) {
if (color[v] == 1) return true; // back edge → cycle
if (color[v] == 0 && dfs(adj, v, color)) return true;
}
color[u] = 2;
return false;
}
Real uses: deadlock detection (cycles in a "waits-for" graph, which database lock managers check), circular imports (Go refuses import cycles), spreadsheet circular references, and Spring's circular bean dependency errors.
Topological sort
A topological order of a DAG lists the vertices so that every edge u → v has u before v. It's "an order in which to do tasks so that dependencies come first." It exists if and only if the graph has no directed cycle. There are two algorithms, both O(V + E):
- Kahn's algorithm (BFS-style): compute in-degrees and enqueue all vertices with in-degree 0. Repeatedly dequeue one, output it, and decrement its neighbours' in-degrees, enqueuing any that drop to 0. If fewer than V vertices were output, the remainder contain a cycle, so it doubles as a cycle detector and tells you which nodes are stuck.
- DFS finish order: run DFS and push each vertex onto a list when it finishes. The reversed list is a topological order.
// Kahn's algorithm: returns an order, or an error if there's a cycle
func TopoSort(n int, edges [][2]int) ([]int, error) {
adj := make([][]int, n)
indeg := make([]int, n)
for _, e := range edges {
adj[e[0]] = append(adj[e[0]], e[1])
indeg[e[1]]++
}
var queue, order []int
for v := 0; v < n; v++ {
if indeg[v] == 0 { queue = append(queue, v) }
}
for len(queue) > 0 {
u := queue[0]
queue = queue[1:]
order = append(order, u)
for _, v := range adj[u] {
indeg[v]--
if indeg[v] == 0 { queue = append(queue, v) }
}
}
if len(order) != n {
return nil, errors.New("cycle detected")
}
return order, nil
}
fn topo_dfs(adj: &[Vec<usize>]) -> Vec<usize> {
fn visit(u: usize, adj: &[Vec<usize>], seen: &mut [bool], out: &mut Vec<usize>) {
seen[u] = true;
for &v in &adj[u] { if !seen[v] { visit(v, adj, seen, out); } }
out.push(u); // post-order: push when finished
}
let mut seen = vec![false; adj.len()];
let mut out = Vec::new();
for u in 0..adj.len() { if !seen[u] { visit(u, adj, &mut seen, &mut out); } }
out.reverse(); // reverse post-order = topological order
out // (assumes a DAG; add colours to detect cycles)
}
Topological sort runs inside every build tool (Make, Gradle, Bazel, Cargo), package manager, task scheduler (Airflow DAGs), database migration runner, spreadsheet recalculation engine, and Spring's bean initialisation. Using a priority queue instead of a FIFO queue in Kahn's algorithm gives the lexicographically smallest order, which is useful for deterministic builds.
Shortest paths: choosing an algorithm
| Situation | Algorithm | Complexity |
|---|---|---|
| Unweighted | BFS | O(V + E) |
| Weights 0 or 1 | 0-1 BFS with a deque | O(V + E) |
| Non-negative weights, single source | Dijkstra with a binary heap | O((V + E) log V) |
| Negative weights allowed, single source; detect negative cycles | Bellman–Ford | O(V · E) |
| DAG (any weights) | Relax edges in topological order | O(V + E) |
| All pairs, dense graph | Floyd–Warshall | O(V³) |
| All pairs, sparse, negative edges | Johnson's (Bellman–Ford reweighting + V × Dijkstra) | O(V·E log V) |
| One target, with a good distance estimate | A* | Depends on the heuristic |
All of them rely on relaxation: if dist[u] + w(u,v) < dist[v], we've found a better route to v through u, so update it.
Dijkstra's algorithm
Keep a min-priority queue of (distance, vertex). Repeatedly pop the closest unsettled vertex. Its distance is now final, because every other route to it would pass through a vertex at least as far away, and non-negative weights can't make a longer prefix shorter. Then relax its outgoing edges.
use std::cmp::Reverse;
use std::collections::BinaryHeap;
/// adj[u] = list of (v, weight). Returns shortest distances from src (u64::MAX = unreachable).
fn dijkstra(adj: &[Vec<(usize, u64)>], src: usize) -> Vec<u64> {
let mut dist = vec![u64::MAX; adj.len()];
let mut heap = BinaryHeap::new();
dist[src] = 0;
heap.push(Reverse((0u64, src)));
while let Some(Reverse((d, u))) = heap.pop() {
if d > dist[u] { continue; } // stale entry: lazy deletion instead of decrease-key
for &(v, w) in &adj[u] {
let nd = d + w;
if nd < dist[v] {
dist[v] = nd;
heap.push(Reverse((nd, v)));
}
}
}
dist
}
record Edge(int to, long w) {}
static long[] dijkstra(List<List<Edge>> adj, int src) {
long[] dist = new long[adj.size()];
Arrays.fill(dist, Long.MAX_VALUE);
dist[src] = 0;
PriorityQueue<long[]> pq = new PriorityQueue<>(Comparator.comparingLong(a -> a[0]));
pq.add(new long[]{0, src});
while (!pq.isEmpty()) {
long[] top = pq.poll();
long d = top[0]; int u = (int) top[1];
if (d > dist[u]) continue; // skip stale entries
for (Edge e : adj.get(u)) {
long nd = d + e.w();
if (nd < dist[e.to()]) { dist[e.to()] = nd; pq.add(new long[]{nd, e.to()}); }
}
}
return dist;
}
type item struct{ d, v int }
type pq []item
func (p pq) Len() int { return len(p) }
func (p pq) Less(i, j int) bool { return p[i].d < p[j].d }
func (p pq) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p *pq) Push(x any) { *p = append(*p, x.(item)) }
func (p *pq) Pop() any { o := *p; it := o[len(o)-1]; *p = o[:len(o)-1]; return it }
func Dijkstra(adj [][]struct{ to, w int }, src int) []int {
dist := make([]int, len(adj))
for i := range dist { dist[i] = math.MaxInt }
dist[src] = 0
h := &pq{{0, src}}
for h.Len() > 0 {
cur := heap.Pop(h).(item)
if cur.d > dist[cur.v] { continue }
for _, e := range adj[cur.v] {
if nd := cur.d + e.w; nd < dist[e.to] {
dist[e.to] = nd
heap.Push(h, item{nd, e.to})
}
}
}
return dist
}
Negative edges break Dijkstra. A vertex is "settled" too early if a later negative edge could have reached it more cheaply. To recover the actual path, store prev[v] = u whenever you relax and walk back from the target. Routing protocols (OSPF, IS-IS) run Dijkstra on the network map at each router, and map applications run Dijkstra-derived algorithms with heavy precomputation (contraction hierarchies).
Bellman–Ford
Relax every edge, V − 1 times. After pass k, every shortest path that uses at most k edges is correct. A shortest path without cycles has at most V − 1 edges, so V − 1 passes suffice. Then do one more pass: if anything still improves, a negative-weight cycle is reachable, and "shortest path" is undefined because you could loop forever and keep getting cheaper.
// Returns false if a negative cycle is reachable from src.
bool bellman_ford(int n, const std::vector<std::tuple<int,int,long long>>& edges,
int src, std::vector<long long>& dist) {
const long long INF = LLONG_MAX / 4;
dist.assign(n, INF);
dist[src] = 0;
for (int pass = 0; pass < n - 1; ++pass) {
bool changed = false;
for (auto [u, v, w] : edges)
if (dist[u] != INF && dist[u] + w < dist[v]) { dist[v] = dist[u] + w; changed = true; }
if (!changed) break; // early exit when stable
}
for (auto [u, v, w] : edges)
if (dist[u] != INF && dist[u] + w < dist[v]) return false; // still improving → negative cycle
return true;
}
It takes O(V·E): slower than Dijkstra, but it handles negative weights. Distance-vector routing (RIP, early ARPANET) is a distributed Bellman–Ford. Negative-cycle detection finds currency arbitrage: with weights −log(rate), a negative cycle is a loop of trades that multiplies your money.
Floyd–Warshall
For all pairs of vertices, DP over allowed intermediate vertices. dist[i][j] after considering intermediates {0 … k} is the minimum of the old value and dist[i][k] + dist[k][j]:
for (int k = 0; k < n; k++) // k MUST be the outermost loop
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (d[i][k] + d[k][j] < d[i][j]) d[i][j] = d[i][k] + d[k][j];
// use a large-but-safe INF (e.g. Long.MAX_VALUE / 4) so INF + INF doesn't overflow
It takes O(V³) time and O(V²) memory, so it's fine up to a few hundred vertices. It handles negative edges, and a negative value on the diagonal (d[i][i] < 0) reveals a negative cycle. A boolean version computes transitive closure ("can i reach j at all?").
A* search
A* is Dijkstra with a sense of direction. The priority is g(v) + h(v), where g is the cost so far and h is a heuristic estimate of the remaining cost to the goal. If h never overestimates (it's admissible), A* still finds an optimal path, and it explores far fewer vertices. With h = 0 it is Dijkstra. On grid maps, use Manhattan distance (4-directional moves) or Euclidean distance as h. Games, robot navigation and puzzle solvers (the 15-puzzle) use it.
Minimum spanning trees: Kruskal and Prim
A spanning tree of a connected, undirected, weighted graph connects all V vertices with V − 1 edges and no cycles. A minimum spanning tree (MST) has the smallest total weight. Think of laying cable to connect every building as cheaply as possible.
Both classic algorithms are greedy and rely on the cut property: for any partition of the vertices into two sides, the lightest edge crossing it belongs to some MST.
- Kruskal: sort all edges by weight. Add each edge unless it would form a cycle, which union-find (chapter 3) checks in near-constant time. O(E log E), dominated by the sort. Best for sparse graphs or edges that arrive as a list.
- Prim: grow one tree from a start vertex, always adding the cheapest edge that leaves the tree, using a priority queue just like Dijkstra. O(E log V). Best for dense graphs with adjacency lists or matrices.
type WEdge struct{ U, V, W int }
func Kruskal(n int, edges []WEdge) (total int, mst []WEdge) {
slices.SortFunc(edges, func(a, b WEdge) int { return cmp.Compare(a.W, b.W) })
d := NewDSU(n) // from chapter 3
for _, e := range edges {
if d.Union(e.U, e.V) { // false if U and V already connected → would make a cycle
total += e.W
mst = append(mst, e)
if len(mst) == n-1 { break }
}
}
return
}
Applications include network and circuit design, approximation algorithms (MST gives a 2-approximation for metric travelling salesman), and clustering. Remove the k − 1 heaviest MST edges and you get k clusters (single-linkage clustering).
Strongly connected components
In a directed graph, a strongly connected component (SCC) is a maximal set of vertices where every vertex can reach every other. Collapsing each SCC into a single node always yields a DAG, the condensation. That's a powerful normalisation: solve the problem on the DAG, then expand.
- Kosaraju (two passes): run DFS and record finish order. Then reverse every edge, and run DFS in decreasing finish order on the reversed graph. Each tree found in the second pass is one SCC. It's simple to remember and O(V + E).
- Tarjan (one pass): DFS keeping, for each vertex, its discovery index and a low-link (the smallest index reachable through its subtree using at most one back edge). Vertices sit on a stack. When a vertex's low-link equals its own index, it's the root of an SCC, so pop the stack down to it. O(V + E).
Uses: finding mutually dependent modules (any SCC with more than one node is an import cycle), 2-SAT solving, deadlock analysis, and finding "clusters" in link graphs.
String algorithms
The pattern-matching problem
Given a text T of length n and a pattern P of length m, find all positions where P occurs in T. The naive algorithm tries each alignment and compares character by character, which is O(n·m) in the worst case (searching for aaaab in aaaaaaaa…). In practice, naive matching with memchr for the first character is fast for typical text. The smarter algorithms matter for worst cases, huge inputs, and streams.
The prefix function and KMP
Knuth–Morris–Pratt never moves backward in the text. When a mismatch happens after matching q characters, the pattern itself tells you how far you can shift. The prefix function π[i] is the length of the longest proper prefix of P[0..i] that is also a suffix of it.
P = a b a b a c a
i = 0 1 2 3 4 5 6
π = 0 0 1 2 3 0 1
π[4] = 3 because "aba" is both a prefix and a suffix of "ababa"
On a mismatch after matching q characters, fall back to q = π[q−1] and keep comparing the same text character. Each text character is examined at most a constant number of times (amortised), so the whole search is O(n + m).
fn prefix_function(p: &[u8]) -> Vec<usize> {
let mut pi = vec![0; p.len()];
let mut k = 0;
for i in 1..p.len() {
while k > 0 && p[i] != p[k] { k = pi[k - 1]; } // fall back
if p[i] == p[k] { k += 1; }
pi[i] = k;
}
pi
}
fn kmp_search(text: &[u8], p: &[u8]) -> Vec<usize> {
if p.is_empty() { return vec![]; }
let pi = prefix_function(p);
let (mut q, mut hits) = (0, Vec::new());
for (i, &c) in text.iter().enumerate() {
while q > 0 && c != p[q] { q = pi[q - 1]; }
if c == p[q] { q += 1; }
if q == p.len() { hits.push(i + 1 - q); q = pi[q - 1]; } // match ends at i
}
hits
}
static int[] prefixFunction(String p) {
int[] pi = new int[p.length()];
for (int i = 1, k = 0; i < p.length(); i++) {
while (k > 0 && p.charAt(i) != p.charAt(k)) k = pi[k - 1];
if (p.charAt(i) == p.charAt(k)) k++;
pi[i] = k;
}
return pi;
}
static List<Integer> kmp(String t, String p) {
int[] pi = prefixFunction(p);
List<Integer> hits = new ArrayList<>();
for (int i = 0, q = 0; i < t.length(); i++) {
while (q > 0 && t.charAt(i) != p.charAt(q)) q = pi[q - 1];
if (t.charAt(i) == p.charAt(q)) q++;
if (q == p.length()) { hits.add(i - q + 1); q = pi[q - 1]; }
}
return hits;
}
A neat trick: compute π over P + "#" + T, where # appears in neither string. Every position where π equals m marks a match. The prefix function also answers "what's the shortest period of this string?" in O(n): the answer is n − π[n−1].
The Z algorithm
The Z-array of a string S gives, for each position i, the length of the longest substring starting at i that matches a prefix of S. It's computed in O(n) by maintaining a window [l, r) of the rightmost prefix-match found so far, and reusing values inside it.
S = a a b x a a b
Z = - 1 0 0 3 1 0 Z[4] = 3: "aab" at position 4 matches the prefix "aab"
For pattern matching, compute Z over P + "$" + T. Every position with Z = m is a match. KMP and Z solve the same problems with the same complexity. Z is often easier to reason about, while KMP's automaton form works on streams.
std::vector<int> z_function(const std::string& s) {
int n = s.size();
std::vector<int> z(n, 0);
for (int i = 1, l = 0, r = 0; i < n; ++i) {
if (i < r) z[i] = std::min(r - i, z[i - l]); // reuse inside the window
while (i + z[i] < n && s[z[i]] == s[i + z[i]]) ++z[i]; // extend naively
if (i + z[i] > r) { l = i; r = i + z[i]; } // move the window right
}
return z;
}
Rolling hashes and Rabin–Karp
Rabin–Karp compares hashes of each length-m window with the hash of P, and checks characters only when the hashes match. The trick is a rolling hash: a polynomial hash can be updated in O(1) as the window slides by one character.
h(s[i..i+m)) = s[i]·B^(m−1) + s[i+1]·B^(m−2) + … + s[i+m−1] (mod M)
slide right: h' = (h − s[i]·B^(m−1)) · B + s[i+m] (mod M)
It's expected O(n + m) and worst case O(n·m) if many hashes collide. Use a large prime modulus or 64-bit overflow arithmetic, and randomise the base to defeat adversarial inputs. Rolling hashes shine beyond single-pattern search:
- Multiple patterns of the same length at once (plagiarism detection).
- Longest repeated substring via binary search plus a hash set.
- Content-defined chunking: rsync, backup tools (restic, borg) and deduplicating storage cut files where the rolling hash of a window meets a condition. An insertion then shifts only nearby chunk boundaries instead of all of them.
Trie-based matching and Aho–Corasick
To search for many patterns at once (a dictionary of 10,000 banned words, or all virus signatures), build a trie of the patterns (chapter 3), then add failure links. Each trie node's failure link points to the longest proper suffix of its string that is also a prefix of some pattern, which is exactly the prefix function generalised to a trie. That's the Aho–Corasick automaton. It scans the text once in O(n + m_total + matches), regardless of how many patterns there are.
patterns: he, she, his, hers
text: "ushers" → matches: "she" at 1, "he" at 2, "hers" at 2
Aho–Corasick powers grep -F with many fixed strings, intrusion detection systems (Snort), antivirus scanners, and content filters. Related structures for the reverse problem (one text, many queries) are suffix arrays and suffix automata, which index all substrings of a text. Genome search and full-text search engines use them.
Lab: algorithms, measured
Asymptotic analysis tells you how cost grows; experiments tell you where the crossovers are and which assumptions break. Everything below was run (CPython 3.13 and JDK 21); Python makes the operation counts easy to see, and its relative timings follow the same shapes as compiled languages.
Where O(n²) beats O(n log n), and where it collapses
Insertion sort is O(n²), merge sort O(n log n). On random input:
def insertion(a):
a = a[:]
for i in range(1, len(a)):
x = a[i]; j = i - 1
while j >= 0 and a[j] > x: a[j + 1] = a[j]; j -= 1
a[j + 1] = x
return a
n insertion merge sorted() (Timsort) (random input, ms)
16 0.014 0.064 0.003
64 0.090 0.068 0.007
256 1.285 0.302 0.021
1024 24.349 2.155 0.094
4096 413.011 7.647 0.468
At n = 16, insertion sort is 4.5× faster than merge sort: no recursion, no allocation, tight loop. By n = 4,096 it is 54× slower, and every 4× increase in n multiplies its time by about 16 (the n² signature) while merge sort's grows by a little over 4×. This crossover is why production sorts are hybrids: Timsort (Python, Java's object sort) and introsort/pdqsort (C++ std::sort, Rust's sort_unstable) switch to insertion sort for small runs (typically under 16–32 elements). The built-in sorted() is 10–16× faster than the hand-written merge sort mainly because it's written in C, a reminder to use the library sort unless you have a specific reason not to.
Input shape matters as much as size
The same three algorithms plus a naive quicksort (first element as pivot), on 3,000 elements of different shapes:
def quick_first_pivot(a): # naive: first element as pivot
if len(a) <= 1: return a
p = a[0]; return quick_first_pivot([x for x in a[1:] if x < p]) + [p] + quick_first_pivot([x for x in a[1:] if x >= p])
n=3000 naive quicksort merge insertion Timsort (ms)
random 4.3 5.2 279.3 0.41
already sorted 290.4 3.2 0.3 0.02
reversed 289.9 3.3 361.4 0.03
- Naive quicksort is fast on random data and 67× slower on sorted data: the first element is the minimum, so every partition is maximally unbalanced, giving n levels of recursion and O(n²) work (and, in languages without deep stacks, a stack overflow, chapter 2). Sorted input is not exotic: it's the common case of "re-sort a list that's already mostly sorted". Real quicksorts pick pivots by median-of-three or randomly, and introsort switches to heapsort if recursion gets too deep, guaranteeing O(n log n).
- Insertion sort is O(n) on sorted input (0.3 ms, faster than everything except Timsort) and worst on reversed input.
- Timsort exploits existing order: it finds already-sorted (or reversed) runs and merges them, so sorted and reversed inputs take 0.02–0.03 ms, 20× faster than on random data. Real data has runs (appended logs, timestamps, mostly sorted lists), which is why Timsort was designed for it.
The lesson for L4: when an algorithm is slow in production but fast in tests, look at the shape of production inputs, not just their size.
Dynamic programming: counting the overlapping subproblems
Coin change (how many ways to make an amount from coins of 1, 2, 5, 10, 20, 50, 100, 200), three ways:
def naive(amount, i=0): # explore: use coin i again, or move to the next coin
if amount == 0: return 1
if amount < 0 or i == len(coins): return 0
return naive(amount - coins[i], i) + naive(amount, i + 1)
@lru_cache(maxsize=None)
def memo(amount, i=0): ... # identical body, results cached by (amount, i)
def bottom_up(amount):
ways = [1] + [0] * amount # ways[a] = number of ways to make a with coins seen so far
for c in coins:
for a in range(c, amount + 1): ways[a] += ways[a - c]
return ways[amount]
amount 50: ways= 451 naive calls= 61,645 memo distinct states= 638 bottom-up cells= 408 agree=True
amount 100: ways= 4563 naive calls= 945,659 memo distinct states= 1188 bottom-up cells= 808 agree=True
amount 200: ways= 73682 naive calls=22,664,009 memo distinct states= 2188 bottom-up cells= 1608 agree=True
The naive recursion makes 22.7 million calls for amount 200, but there are only 2,188 distinct subproblems (pairs of amount and coin index). Every other call recomputes something already known: that's what "overlapping subproblems" means, made countable. Memoisation solves each state once (top-down, only the states actually reached); the bottom-up table fills 1,608 cells in a fixed order and needs only one array of size amount + 1. Design the state (here: amount and which coins are still allowed; ordering coins this way counts combinations rather than permutations) and the transition (use this coin again, or move on), and the rest is bookkeeping.
String search on an adversarial input
Searching for "a"×1000 + "b" in "a"×100,000 + "b":
naive found at 99000, character comparisons: 99,100,001
kmp found at 99000, character comparisons: 199,001
The naive search compares up to 1,000 characters at almost every position before failing: O(n·m), 99 million comparisons. KMP's prefix function remembers how much of the pattern still matches after a mismatch, so it never moves backwards in the text: O(n + m), 199,001 comparisons, 500× fewer. On ordinary text the naive approach is fine (mismatches happen at the first character), which is why the adversarial case is what matters: if users control the pattern or the text, naive matching is a denial-of-service vector. The same holds for regular expressions with backtracking engines (catastrophic backtracking, "ReDoS"); RE2, Rust's regex and Go's regexp use automata with linear-time guarantees.
Greedy assumptions break: Dijkstra with a negative edge
Dijkstra's algorithm is greedy: once a node is popped from the priority queue, its distance is treated as final. That's only correct when no edge is negative. A graph with one negative edge (think of a rebate on one route):
edges = [("A", "B", 4), ("A", "C", 2), ("B", "D", 1), ("C", "D", 5), ("B", "C", -4)]
Dijkstra: {'A': 0, 'B': 4, 'C': 2, 'D': 5}
Bellman-Ford: {'A': 0, 'B': 4, 'C': 0, 'D': 5} negative cycle: False
Dijkstra finalised C at distance 2 (via A→C) before discovering that A→B→C costs 4 − 4 = 0. Bellman-Ford relaxes every edge n − 1 times, so it finds the true distance, and one more pass detects negative cycles (where "shortest" is undefined). The exchange-argument proof of Dijkstra's correctness relies on "extending a path never makes it shorter", which a negative edge violates: a concrete example of why knowing a greedy algorithm's proof tells you exactly when not to use it.
An overflow in the most famous algorithm
Binary search's midpoint, computed three ways in Java, for indices beyond 1.07 billion:
int lo = 1_500_000_000, hi = 2_000_000_000;
System.out.println("(lo + hi) / 2 = " + (lo + hi) / 2);
System.out.println("lo + (hi - lo) / 2 = " + (lo + (hi - lo) / 2));
System.out.println("(lo + hi) >>> 1 = " + ((lo + hi) >>> 1));
(lo + hi) / 2 = -397483648
lo + (hi - lo) / 2 = 1750000000
(lo + hi) >>> 1 = 1750000000
lo + hi exceeds Integer.MAX_VALUE and wraps negative (two's complement, chapter 6). This bug sat in the JDK's Arrays.binarySearch and in the textbook Programming Pearls version for about two decades before Joshua Bloch reported it in 2006. The unsigned shift works because the true sum fits in 32 unsigned bits; lo + (hi − lo) / 2 never overflows at all. Proving an algorithm correct on mathematical integers is not the same as proving it correct on machine integers.
Revision sheet: algorithms
Key ideas
- Judge an algorithm by correctness (every valid input), termination, and cost in time and space as a function of input size.
- Big-O gives an upper bound on growth, Big-Ω a lower bound, Big-Θ a tight bound. Analyse worst, average and amortised cases separately.
- Searching: linear O(n) on anything; binary O(log n) on sorted data; hashing O(1) average.
- Sorting: comparison sorts can't beat Ω(n log n). Merge sort is O(n log n) and stable; quicksort O(n log n) on average, O(n²) worst; heapsort O(n log n) in place; insertion sort wins on tiny or nearly sorted input. Counting/radix sort beat n log n by not comparing. Libraries use hybrids (Timsort for Python and Java objects, introsort in C++ standard libraries, pdqsort-style sorts in Go and Rust).
- Divide and conquer: split, solve recursively, combine; costs follow recurrences like T(n) = 2T(n/2) + n = O(n log n).
- Dynamic programming: when subproblems overlap and the best answer is built from best sub-answers, solve each subproblem once (memoised top-down or tabulated bottom-up).
- Greedy: take the locally best choice; correct only with a proof (exchange argument, matroid structure).
- Graphs: BFS gives shortest paths in unweighted graphs; DFS gives reachability, cycles, topological order; Dijkstra handles non-negative weights; Bellman-Ford handles negative edges; minimum spanning trees by Kruskal or Prim.
- Strings: naive matching O(nm); KMP and Z-algorithm O(n + m); Rabin-Karp by rolling hash.
Numbers to remember
- log₂ of 1 thousand ≈ 10, 1 million ≈ 20, 1 billion ≈ 30.
- A modern core does very roughly 10⁸–10⁹ simple steps per second: O(n²) on n = 10⁵ is about 10¹⁰ steps, too slow for interactive use; O(n log n) on 10⁷ is fine.
- Dijkstra with a binary heap: O((V + E) log V). BFS/DFS: O(V + E).
Pitfalls
- Binary search midpoint
(lo + hi) / 2overflows fixed-size ints; uselo + (hi - lo) / 2. - Quicksort with a fixed pivot on sorted input degrades to O(n²).
- Greedy without a proof (coins 1, 3, 4 for amount 6).
- Recursion depth on large inputs: convert deep recursion to iteration or an explicit stack.
- Dijkstra with negative edge weights gives wrong answers silently.
- Forgetting that hidden constant factors and cache behaviour decide between algorithms of the same Big-O.
Glossary
- Invariant: a condition true before and after every loop iteration, used to prove correctness.
- Stable sort: equal keys keep their original relative order.
- In place: uses O(1) (or O(log n)) extra memory.
- Memoisation: caching a function's results by argument.
- Topological order: an ordering of a directed acyclic graph's vertices with every edge pointing forward.
- Relaxation: improving a distance estimate via an edge, the core step of shortest-path algorithms.