Shelves / Foundations of Computing
CS·05
Discrete Mathematics
The mathematics computing actually runs on: sets, logic, proofs, counting, probability, recurrences and Boolean algebra, each tied back to code.
Start here: the mathematics behind programs
Why programmers need "discrete" mathematics
Discrete mathematics deals with things you can count: whole numbers, yes/no values, objects and the connections between them, as opposed to continuous quantities like the smooth curves of calculus. Computers are discrete machines (everything is bits), so this is their native mathematics. You use it, often without noticing, whenever you:
- write a condition (
if paid and not locked): that's logic; - ask "how many possible passwords?" or "how many test cases cover all combinations?": that's counting;
- estimate "how likely is a collision?" or "what fraction of requests will fail?": that's probability;
- convince yourself a loop is correct: that's proof, usually by induction;
- describe an algorithm's cost in terms of a smaller version of itself: that's a recurrence;
- model a network, a map or dependencies: that's a graph.
Sets: collections without order or duplicates
A set is a collection of distinct items, where order doesn't matter: {dal, paneer, rajma}. The key operations, which Python supports directly:
veg = {"dal", "paneer", "rajma", "aloo"}
favourites = {"paneer", "biryani", "aloo"}
print(sorted(veg | favourites), sorted(veg & favourites), sorted(veg - favourites))
union: ['aloo', 'biryani', 'dal', 'paneer', 'rajma'] | intersection: ['aloo', 'paneer'] | difference veg-fav: ['dal', 'rajma']
- Union (A ∪ B,
|): items in either. - Intersection (A ∩ B,
&): items in both. - Difference (A − B,
-): items in A but not B. - Membership (x ∈ A,
in): is x one of them?
Databases are built on this: SQL's UNION, INTERSECT and EXCEPT are set operations, and a WHERE clause selects a subset.
Logic: true, false, and, or, not
Propositional logic combines statements that are true or false. A truth table lists every combination:
A B A and B A or B not A A→B
False False False False True True
False True False True True True
True False False True False False
True True True True False True
- and is true only when both are true; or when at least one is (including both); not flips.
- Implication "if A then B" (A → B) is false only when A is true and B is false. "If it rains, I take an umbrella" is broken only by a rainy day without an umbrella; on dry days the promise isn't broken whatever you carry. This trips up many people; the last column shows it.
- De Morgan's laws say how
notdistributes: not (A and B) = (not A) or (not B); not (A or B) = (not A) and (not B). They're how you simplify conditions safely ("not (paid and active)" means "unpaid or inactive").
Counting: how many possibilities?
Two rules underlie nearly all counting:
- Rule of product: if one choice has m options and an independent second choice has n, together there are m × n combinations. A 4-digit PIN: 10 × 10 × 10 × 10 = 10,000.
- Rule of sum: if you choose either from m options or from n separate options, there are m + n.
Arrangements and selections:
- Permutations: choosing k items in order from n. Three dishes for Monday, Tuesday and Wednesday from five: 5 × 4 × 3 = 60.
- Combinations: choosing k items where order doesn't matter. A team of 3 from 5 people: 60 ordered choices, but each team appears 3 × 2 × 1 = 6 ways, so 60 / 6 = 10. Written C(5, 3) or "5 choose 3".
4-digit PIN codes: 10000 | 3 dishes chosen in order from 5: 60 | teams of 3 from 5: 10 = 10
Counting tells you whether brute force is feasible (try every possibility?), how strong a password is, and how many test combinations exist.
Probability: counting favourable outcomes
When all outcomes are equally likely, probability = favourable outcomes ÷ all outcomes. Two dice have 6 × 6 = 36 outcomes; six of them sum to 7 (1+6, 2+5, 3+4, 4+3, 5+2, 6+1), so P(7) = 6/36 = 1/6. A simulation agrees:
outcomes = list(product(range(1, 7), repeat=2))
sevens = [o for o in outcomes if sum(o) == 7]
sim = sum(random.randint(1, 6) + random.randint(1, 6) == 7 for _ in range(100_000)) / 100_000
P(sum = 7): counted 6/36 = 0.1667, simulated 0.1662
expected winnings per play: -0.33 rupees
The expected value is the long-run average: a game that pays ₹10 for rolling a six and costs ₹2 to play is worth (1/6) × 10 − 2 ≈ −₹0.33 per play: on average you lose. Programmers use probability for failure rates, collisions, random algorithms, A/B tests and capacity planning. Two key rules: for independent events, multiply probabilities (P(both) = P(A) × P(B)); and P(not A) = 1 − P(A). The lab shows what happens when "independent" isn't true.
Proof and induction: knowing, not hoping
Testing a program on 1,000 inputs gives evidence; a proof gives certainty for every input. Mathematical induction proves a statement for all whole numbers, like dominoes:
- Base case: show it's true for the first number (the first domino falls).
- Inductive step: show that if it's true for some n, then it's true for n + 1 (each domino knocks over the next).
Example: 1 + 2 + … + n = n(n + 1)/2. Base: for n = 1, both sides are 1. Step: if the formula holds for n, then 1 + … + n + (n + 1) = n(n + 1)/2 + (n + 1) = (n + 1)(n + 2)/2, which is the formula for n + 1. So it holds for every n. The program below checks the first thousand cases; the proof covers all of them:
formula holds for n = 1..1000: True
Programmers use exactly this reasoning for loops (a loop invariant is an induction hypothesis: true before the loop, kept true by each iteration) and for recursive functions (the base case, plus "if the smaller calls are right, this call is right").
Recurrences, graphs and Boolean algebra in one paragraph each
- A recurrence describes a quantity in terms of smaller cases: the stair-climbing count ways(n) = ways(n − 1) + ways(n − 2) from chapter 4, or merge sort's cost T(n) = 2T(n/2) + n. Solving recurrences tells you an algorithm's growth rate.
- A graph is a set of vertices (points) and edges (connections), directed or not, weighted or not. Maps, networks, dependencies and social connections are graphs; a tree is a connected graph with no cycles.
- Boolean algebra is logic written as algebra with values 0 and 1: AND as multiplication, OR as (saturating) addition, NOT as 1 − x. Digital circuits are built from it (chapter 7), and it lets you simplify conditions mechanically.
Check yourself
How deep to go in discrete mathematics
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 | Read set, logic and combinatorics notation |
| L2 | Use the tools: count cases, compute probabilities, write invariants, simplify Boolean expressions |
| L3 | Prove things: induction for loops and recursion, counting arguments for bounds, pigeonhole for impossibility |
| L4 | Spot mathematical errors in code and estimates: off-by-one counts, wrong independence assumptions, birthday-paradox collisions |
| L5 | Model problems mathematically to choose designs (hash sizes, sharding, retry probabilities, capacity) |
| L6 | Use these models to reason about production risk: failure probabilities, collision budgets, statistical alerting |
Why discrete mathematics
Continuous versus discrete
Calculus studies quantities that vary smoothly. Discrete mathematics studies things you can count: integers, bits, nodes, steps, true/false. Computers are discrete machines, so this is their native mathematics. It gives you a precise language for specifications ("for every request there exists a response"), tools to prove that code is correct (induction proves loops and recursion correct), ways to count possibilities (how many test cases? how likely is a hash collision?), and the algebra behind circuits, query optimisers and type systems.
This chapter teaches each idea with the notation, a worked example, and where it shows up in software.
Sets
Sets and set notation
A set is an unordered collection of distinct objects, called elements. Write x ∈ A for "x is an element of A" and x ∉ A for "it isn't."
- Roster notation lists the elements: A = {2, 3, 5, 7}.
- Set-builder notation describes a property: B = {x ∈ ℤ | x > 0 and x is even}, read "the set of integers x such that x is positive and even."
- Standard sets: ℕ (naturals, which in CS usually include 0), ℤ (integers), ℚ (rationals), ℝ (reals), and ∅ (the empty set, with no elements).
- Cardinality |A| is the number of elements. |{2, 3, 5, 7}| = 4 and |∅| = 0.
- Subset: A ⊆ B if every element of A is in B. A proper subset A ⊂ B also requires A ≠ B. ∅ is a subset of every set.
- Equality: A = B if and only if A ⊆ B and B ⊆ A. That's how you prove two sets are equal: prove inclusion both ways.
Order and repetition don't matter: {1, 2, 2, 3} = {3, 1, 2}. When order matters you want a tuple (sequence), and when repetition matters you want a multiset (bag).
Set operations
| Operation | Notation | Definition | In code |
|---|---|---|---|
| Union | A ∪ B | x in A or B | a.union(&b), addAll, SQL UNION |
| Intersection | A ∩ B | x in A and B | a.intersection(&b), retainAll, SQL INTERSECT, INNER JOIN on keys |
| Difference | A − B (or A \ B) | x in A and not in B | a.difference(&b), removeAll, SQL EXCEPT |
| Symmetric difference | A △ B | in exactly one of them | a.symmetric_difference(&b), XOR of bitsets |
| Complement | Aᶜ or Ā | x in the universe U but not in A | bitwise NOT on a bitset |
| Cartesian product | A × B | all ordered pairs (a, b) | nested loops, SQL CROSS JOIN |
| Power set | 𝒫(A) | the set of all subsets of A | iterate bitmasks 0 … 2ⁿ − 1 |
Two facts worth memorising: |A × B| = |A| · |B|, and |𝒫(A)| = 2^|A|, because each element is either in a subset or not.
De Morgan's laws for sets: (A ∪ B)ᶜ = Aᶜ ∩ Bᶜ and (A ∩ B)ᶜ = Aᶜ ∪ Bᶜ. The same laws appear in logic and Boolean algebra below, because all three are the same algebra.
Inclusion–exclusion counts unions without double counting:
|A ∪ B| = |A| + |B| − |A ∩ B|
|A ∪ B ∪ C| = |A| + |B| + |C| − |A∩B| − |A∩C| − |B∩C| + |A∩B∩C|
Example: how many integers from 1 to 100 are divisible by 3 or 5? |div3| = 33, |div5| = 20, and |div15| = 6, so 33 + 20 − 6 = 47.
Sets in code: bitsets
When the universe is small (say up to 64 elements), a set can be a single machine word. Bit i is 1 when element i is present. Every set operation becomes one CPU instruction:
let a: u64 = 0b1011; // {0, 1, 3}
let b: u64 = 0b0110; // {1, 2}
let union = a | b; // {0,1,2,3}
let inter = a & b; // {1}
let diff = a & !b; // {0, 3}
let sym = a ^ b; // {0, 2, 3}
let size = a.count_ones(); // |A| = 3 (POPCNT instruction)
let has3 = a & (1 << 3) != 0;
// iterate all subsets of a: the classic "submask" loop
let mut s = a;
loop { /* use s */ if s == 0 { break; } s = (s - 1) & a; }
a, b := uint64(0b1011), uint64(0b0110)
union, inter, diff := a|b, a&b, a&^b // Go has an AND NOT operator: &^
size := bits.OnesCount64(a)
_ = union; _ = inter; _ = diff; _ = size
long a = 0b1011, b = 0b0110;
long union = a | b, inter = a & b, diff = a & ~b;
int size = Long.bitCount(a);
// For larger universes: java.util.BitSet, or EnumSet (a bitset over enum constants)
EnumSet<DayOfWeek> weekend = EnumSet.of(DayOfWeek.SATURDAY, DayOfWeek.SUNDAY);
// Zig's std.bit_set and std.EnumSet give typed bitsets of any size
const Perm = enum { read, write, exec };
var p = std.EnumSet(Perm).initEmpty();
p.insert(.read);
p.insert(.write);
const can_write = p.contains(.write);
Unix file permissions (rwx bits), feature flags, the CPU's flag register, chess engines' bitboards (one u64 per piece type, one bit per square), and SQL bitmap indexes all use this representation.
Relations
Relations and their properties
A binary relation R from A to B is a subset of A × B. We write a R b when (a, b) ∈ R. "Is less than," "is a parent of," "follows," "depends on" and "has the same hash as" are all relations. A database table is a relation, which is where the name relational database comes from. When A = B, we say R is a relation on A, and four properties matter:
| Property | Definition | Example | Non-example |
|---|---|---|---|
| Reflexive | a R a for all a | ≤, =, "same birthday as" | < |
| Symmetric | a R b ⇒ b R a | =, "is a sibling of", "is friends with" | ≤, "follows" |
| Antisymmetric | a R b and b R a ⇒ a = b | ≤, ⊆, "divides" (on positive ints) | "is friends with" |
| Transitive | a R b and b R c ⇒ a R c | <, ≤, =, "is an ancestor of", "depends on" (transitively) | "is a parent of", "is friends with" |
The transitive closure of R is the smallest transitive relation containing it: "can reach in one or more steps." Computing it is graph reachability: Floyd–Warshall's boolean version (Warshall's algorithm), or BFS from each node.
Equivalence relations
A relation that is reflexive, symmetric and transitive is an equivalence relation. It partitions the set into disjoint equivalence classes, groups of mutually related elements. Examples:
- "Same remainder mod n" partitions ℤ into n classes, the residue classes. This is what
hash % bucketsdoes. - "Same connected component" in an undirected graph. Union-find (chapter 3) maintains exactly these classes.
equals()in Java must be an equivalence relation. TheObject.equalscontract states reflexivity, symmetry and transitivity explicitly, and a broken one breaksHashSetandHashMap. A classic bug:class ColorPoint extends Pointwith anequalsthat compares colours breaks symmetry with plainPoints. Effective Java item 10 discusses it.- Rust's
Eqtrait (as opposed toPartialEq) promises a full equivalence relation.f64is onlyPartialEqbecause NaN ≠ NaN breaks reflexivity.
Order relations
A relation that is reflexive, antisymmetric and transitive is a partial order (≤ on numbers, ⊆ on sets, "divides" on positive integers, "happened-before" in distributed systems, dependency order in a DAG). "Partial" means some pairs may be incomparable: neither {1} ⊆ {2} nor {2} ⊆ {1}.
A total (linear) order additionally makes every pair comparable: a ≤ b or b ≤ a. Sorting needs a total order, or at least a strict weak ordering, where "equivalent" elements are allowed. That's the formal requirement behind every comparator, and why the chapter 4 warning about inconsistent comparators matters.
A topological sort (chapter 4) is a way to extend a partial order (a DAG) into a total order. Vector clocks in distributed systems (Part V) define a partial order on events. Concurrent events are exactly the incomparable ones.
Functions
Functions, domain and codomain
A function f : A → B assigns to every element of the domain A exactly one element of the codomain B. The image (range) is the set of values actually produced. Formally, a function is a relation in which each a appears in exactly one pair.
- A partial function is undefined on some inputs: integer division by zero,
headof an empty list,HashMap.geton a missing key. Programming languages model partiality with exceptions,Option,null, or panics. - A pure function in programming is a mathematical function. Side effects make "functions" in code something more general.
Injective, surjective and bijective
| Property | Meaning | Example | Consequence |
|---|---|---|---|
| Injective (one-to-one) | Distinct inputs give distinct outputs | f(x) = 2x on ℤ | It can be inverted on its image; it loses no information |
| Surjective (onto) | Every element of the codomain is hit | f(x) = x mod 10, ℤ → | No output value is wasted |
| Bijective | Both | f(x) = x + 1 on ℤ; any permutation | It has an inverse f⁻¹; the sets have equal size |
These ideas run through software:
- A hash function from strings to 64-bit integers can't be injective, since infinitely many inputs map to finitely many outputs. That is the pigeonhole principle, and it's why collisions are inevitable.
- Encryption must be a bijection on blocks, or decryption would be ambiguous. Compression must be injective, or two inputs would decompress to the same output, and by counting, no lossless compressor can shrink every input.
- Database keys should map rows injectively to identifiers.
- Serialisation should be injective, so that two different objects never produce the same bytes. Round-trip tests check
decode(encode(x)) == x.
Composition: (g ∘ f)(x) = g(f(x)). It's associative, which is why pipelines and middleware chains can be grouped any way you like. The identity function id(x) = x is the neutral element of composition.
The pigeonhole principle
If you put n + 1 items into n boxes, some box gets at least two. More generally, n items in k boxes means some box has at least ⌈n/k⌉. It sounds trivial, but it proves a lot:
- Any hash function into a smaller space has collisions.
- Any lossless compressor makes some inputs longer.
- Among 367 people, two share a birthday. The birthday paradox (below) shows you only need 23 for a 50% chance.
- In any sequence of n² + 1 distinct numbers there is an increasing or decreasing subsequence of length n + 1 (Erdős–Szekeres).
Logic
Propositional logic
A proposition is a statement that is either true or false: "x > 5," "the file exists." Propositional logic combines propositions with connectives:
| Connective | Symbol | Read as | In code | True when |
|---|---|---|---|---|
| Negation | ¬p | not p | !p |
p is false |
| Conjunction | p ∧ q | p and q | p && q |
both true |
| Disjunction | p ∨ q | p or q | p \|\| q |
at least one true |
| Exclusive or | p ⊕ q | p xor q | p != q, p ^ q |
exactly one true |
| Implication | p → q | if p then q | !p \|\| q |
false only when p is true and q is false |
| Biconditional | p ↔ q | p iff q | p == q |
both have the same value |
Implication confuses people because "if p then q" is true whenever p is false. This is called vacuous truth. "If it's raining, the ground is wet" isn't violated on a dry, sunny day. In code, a precondition check assert(!p || q) reads "p implies q."
Truth tables define the connectives and let you check any formula mechanically:
p q │ p→q ¬q→¬p ¬p∨q q→p
─────┼──────────────────────
T T │ T T T T
T F │ F F F T
F T │ T T T F
F F │ T T T T
Columns 1–3 are identical: p → q is logically equivalent to its contrapositive ¬q → ¬p and to ¬p ∨ q. The converse q → p is not equivalent, and confusing them is the most common logic error in arguments and specifications.
A formula that is always true is a tautology (p ∨ ¬p). One that is always false is a contradiction (p ∧ ¬p). One that is true for some assignment is satisfiable. Deciding satisfiability is SAT, the first problem proved NP-complete (Cook, 1971). Modern SAT solvers handle millions of variables in practice and power package dependency resolution (dnf, conda, Dart's pub), hardware verification, and test generation.
Logical laws and simplifying conditions
These equivalences let you simplify conditionals:
| Law | Form |
|---|---|
| Double negation | ¬¬p ≡ p |
| De Morgan | ¬(p ∧ q) ≡ ¬p ∨ ¬q; ¬(p ∨ q) ≡ ¬p ∧ ¬q |
| Distributive | p ∧ (q ∨ r) ≡ (p ∧ q) ∨ (p ∧ r) |
| Absorption | p ∨ (p ∧ q) ≡ p |
| Implication | p → q ≡ ¬p ∨ q |
| Contrapositive | p → q ≡ ¬q → ¬p |
// Before: nested negations are hard to read
if (!(user == null || !user.isActive() || user.isBanned())) { … }
// De Morgan: ¬(a ∨ b ∨ c) ≡ ¬a ∧ ¬b ∧ ¬c
if (user != null && user.isActive() && !user.isBanned()) { … }
Predicates and quantifiers
Propositional logic can't say "every user has an email." Predicate (first-order) logic adds:
- Predicates: propositions with variables, such as P(x) = "x is prime" or Admin(u).
- Universal quantifier ∀x P(x): P holds for every x in the domain.
- Existential quantifier ∃x P(x): P holds for at least one x.
Negating a quantifier swaps it, which is De Morgan again:
¬∀x P(x) ≡ ∃x ¬P(x) "not all requests succeeded" ≡ "some request failed"
¬∃x P(x) ≡ ∀x ¬P(x) "no user is an admin" ≡ "every user is not an admin"
Order of nested quantifiers matters. "∀ request ∃ server that handles it" (every request is handled by some server) is very different from "∃ server ∀ request it handles" (one server handles everything).
Quantifiers are loops and query operators:
| Logic | Code | SQL |
|---|---|---|
| ∀x ∈ S: P(x) | s.iter().all(p), stream.allMatch(p) |
NOT EXISTS (… WHERE NOT p) |
| ∃x ∈ S: P(x) | s.iter().any(p), stream.anyMatch(p) |
EXISTS (… WHERE p) |
| ¬∃x: P(x) | !s.iter().any(p), noneMatch(p) |
NOT EXISTS |
Over the empty set, all is true (vacuously) and any is false, consistently in every language: [].iter().all(…) == true. That follows directly from the logic.
Specifications, database constraints, access-control policies (Rego, Cedar), formal methods tools (TLA+, Alloy, Dafny) and property-based tests ("for all inputs, decode(encode(x)) == x") are all predicate logic.
Proofs
Why programmers need proofs
A test shows your code works on the inputs you tried. A proof shows it works on all inputs. You won't formally prove most production code, but proof thinking (stating invariants, considering every case, arguing why a loop terminates) is how you design correct algorithms and catch the cases tests miss. Chapter 4's binary search invariant and greedy exchange argument were proofs.
Proof techniques
| Technique | Structure | Example |
|---|---|---|
| Direct proof | Assume the hypothesis, derive the conclusion step by step | If n is odd, n² is odd: n = 2k+1 ⇒ n² = 4k²+4k+1 = 2(2k²+2k)+1 |
| Contrapositive | Prove ¬q → ¬p instead of p → q | If n² is even then n is even. Equivalent: if n is odd then n² is odd (above) |
| Contradiction | Assume the statement is false, derive something impossible | √2 is irrational; infinitely many primes |
| Cases (exhaustion) | Split into cases that cover everything, prove each | |
| Construction | Prove ∃ by exhibiting an example | "There is a sorting network for 4 inputs with 5 comparators": draw it |
| Counterexample | Disprove ∀ with one case | "All odd numbers are prime": 9 |
| Induction | Base case + inductive step (next section) | Sum formulas, loop invariants, recursive correctness |
| Pigeonhole / counting | Count two ways, or overflow boxes | Hash collisions; no universal compressor |
Euclid's proof that there are infinitely many primes (by contradiction): suppose there are finitely many, p₁ … pₖ. Let N = p₁·p₂·…·pₖ + 1. Dividing N by any pᵢ leaves remainder 1, so no pᵢ divides N. But N > 1 has some prime factor, which isn't in the list. Contradiction. ∎
Diagonalisation is a contradiction proof with enormous consequences. Cantor used it to show the reals are uncountable. Turing used it to show the halting problem is undecidable: suppose halts(program, input) existed. Build paradox(p) { if halts(p, p) loop forever; else return; }. Then paradox(paradox) halts if and only if it doesn't. So no general program can decide whether arbitrary programs halt. That's why linters, type checkers and static analysers are necessarily conservative: they must sometimes reject correct programs or miss bugs (Rice's theorem).
Mathematical induction
Ordinary induction
Induction proves a statement P(n) for all n ≥ n₀, like knocking over infinite dominoes:
- Base case: prove P(n₀).
- Inductive step: assume P(k) (the inductive hypothesis) and prove P(k + 1).
Since P(n₀) holds and each case implies the next, it holds for every n ≥ n₀.
Example. Prove 1 + 2 + … + n = n(n+1)/2 for all n ≥ 1.
- Base (n = 1): the left side is 1, and the right side is 1·2/2 = 1. ✓
- Step: assume 1 + … + k = k(k+1)/2. Then 1 + … + k + (k+1) = k(k+1)/2 + (k+1) = (k+1)(k/2 + 1) = (k+1)(k+2)/2, which is the formula for n = k+1. ∎
This formula is why nested loops for i in 0..n { for j in 0..i } do about n²/2 iterations, which is O(n²).
Strong and structural induction
- Strong induction: in the step, assume P holds for all values n₀ … k, not just k. This is natural for divide and conquer, where the subproblems are smaller but not just one smaller. Example: every integer n ≥ 2 is a product of primes. Either n is prime, or n = a·b with 2 ≤ a, b < n, and both a and b are products of primes by the strong hypothesis.
- Structural induction: induct over the structure of recursively defined data such as lists, trees and expressions. Prove the property for base constructors (empty list, leaf), then for each recursive constructor, assuming it holds for the parts. Example: a binary tree with n internal nodes, each having exactly 2 children, has n + 1 leaves. Compilers and type systems are proved correct this way: "type checking preserves types" is shown by structural induction over expressions.
Loop invariants: induction for code
A loop invariant is a statement that is true before the loop and after every iteration. It's induction applied to loops. To prove a loop correct, show:
- Initialisation: the invariant holds before the first iteration (base case).
- Maintenance: if it holds before an iteration, it holds after (inductive step).
- Termination: when the loop stops, the invariant plus the exit condition imply the result you want. Also show that the loop does stop, usually because some non-negative quantity strictly decreases.
/// Returns the maximum of a non-empty slice.
fn max(xs: &[i32]) -> i32 {
let mut m = xs[0];
let mut i = 1;
// Invariant: m == max(xs[0..i])
// init: m == xs[0] == max(xs[0..1]) ✓
// maintenance: if xs[i] > m we set m = xs[i], so m == max(xs[0..i+1])
// termination: i == xs.len() ⇒ m == max(xs[0..len]) = the answer.
// It stops because len − i decreases by 1 every iteration.
while i < xs.len() {
if xs[i] > m { m = xs[i]; }
i += 1;
}
m
}
Insertion sort's invariant is "a[0..i] is sorted." Binary search's is "the answer lies in [lo, hi)." Writing the invariant first and then the code that maintains it is the most reliable way to write tricky loops.
Combinatorics
Counting principles
Counting answers questions like "how many test cases cover all combinations?", "how many possible passwords?" and "how many paths through this code?" Two basic rules underlie everything:
- Product rule: if a task is a sequence of independent steps with n₁, n₂, … nₖ choices, there are n₁·n₂·…·nₖ ways in total. An 8-character password over 62 alphanumerics has 62⁸ ≈ 2.2 × 10¹⁴ possibilities. That's about 47.6 bits of entropy (log₂ 62⁸), which a GPU cracking cluster can exhaust against fast hashes.
- Sum rule: if a task can be done in one of several disjoint ways, add the counts. Passwords of length 6, 7 or 8 total 62⁶ + 62⁷ + 62⁸. Use inclusion–exclusion when the ways overlap.
Other tools: the complement (count what you don't want and subtract from the total), bijection (count an easier set that's in one-to-one correspondence), and division (count with overcounting, then divide by how many times each object was counted).
Permutations
A permutation is an ordered arrangement.
- All n distinct objects in order: n! = n·(n−1)·…·1. 10! = 3,628,800. 20! ≈ 2.4 × 10¹⁸, so brute force over orderings stops being feasible around n = 12–15.
- Ordered selections of k from n: P(n, k) = n! / (n − k)!. Gold, silver and bronze among 10 runners: 10·9·8 = 720.
- With repeated items: n! / (n₁!·n₂!·…). The arrangements of "MISSISSIPPI" number 11! / (1!·4!·4!·2!) = 34,650.
Generating permutations: Heap's algorithm produces each one with a single swap. Next-permutation (C++ std::next_permutation) steps through them in lexicographic order. Shuffling uniformly at random uses Fisher–Yates: for i from n−1 down to 1, swap a[i] with a[j] for a uniform random j in [0, i]. Biased "shuffles" such as sorting with a random comparator, or swapping with j in [0, n), are a famous bug class (a 1990s online poker site's shuffle was shown to be predictable this way).
Combinations
A combination is an unordered selection. Choosing k of n distinct items:
C(n, k) = (n choose k) = n! / (k! · (n − k)!)
C(52, 5) = 2,598,960 poker hands. C(n, 2) = n(n−1)/2 is the number of pairs, which is why comparing every pair of n items is O(n²), and why a network of n nodes needs n(n−1)/2 links to be fully connected.
Key identities:
- Symmetry: C(n, k) = C(n, n−k). Choosing what to take is the same as choosing what to leave.
- Pascal's rule: C(n, k) = C(n−1, k−1) + C(n−1, k). The n-th item is either in or out. This is a DP recurrence: it builds Pascal's triangle without factorials (which overflow).
- Binomial theorem: (x + y)ⁿ = Σ C(n, k) xᵏ yⁿ⁻ᵏ. Setting x = y = 1 gives Σₖ C(n, k) = 2ⁿ, which recovers the size of the power set.
- Stars and bars: the number of ways to put n identical items into k distinct boxes is C(n + k − 1, k − 1).
// Pascal's triangle DP: binomial coefficients without factorial overflow
func Binomial(n, k int) uint64 {
if k < 0 || k > n { return 0 }
if k > n-k { k = n - k } // symmetry: smaller loop
row := make([]uint64, k+1)
row[0] = 1
for i := 1; i <= n; i++ {
for j := min(i, k); j > 0; j-- { // right to left so row[j-1] is still the old value
row[j] += row[j-1]
}
}
return row[k]
}
// Binomial(52, 5) == 2598960
In testing: with 10 boolean flags there are 2¹⁰ = 1,024 combinations. Pairwise (all-pairs) testing covers every pair of flag values with far fewer tests (often around 10–20), because most bugs involve at most two interacting factors.
Graph theory and trees
Graph theory fundamentals
Chapter 3 covered graphs as data structures and chapter 4 as algorithms. Here are the mathematical facts that make those algorithms work.
- Handshake lemma: in any undirected graph, Σ deg(v) = 2|E|, because every edge contributes to two degrees. Consequence: the number of odd-degree vertices is always even.
- Paths and walks: a walk may repeat vertices, a path may not. In a graph with V vertices, any shortest path has at most V − 1 edges, which is why Bellman–Ford needs V − 1 passes.
- Bipartite graphs: the vertices split into two sides with every edge crossing between them (users–products, jobs–workers). A graph is bipartite if and only if it has no odd-length cycle. Test it by 2-colouring with BFS. Matching problems (assigning workers to jobs) live here.
- Euler paths: a walk that uses every edge exactly once exists in a connected graph iff it has 0 or 2 odd-degree vertices (Euler, 1736, the Königsberg bridges). It's checkable in linear time. DNA sequence assembly uses Euler paths over de Bruijn graphs.
- Hamiltonian paths: visit every vertex exactly once. It looks similar, but it's NP-complete. No simple degree condition decides it. Small changes in a problem statement can move it from easy to intractable.
- Planar graphs can be drawn without crossing edges. Euler's formula V − E + F = 2 (F = faces) holds for connected planar graphs. The four colour theorem: any planar map can be coloured with 4 colours so neighbours differ.
- Graph colouring: assign colours so that adjacent vertices differ. The minimum number is the chromatic number, NP-hard in general. Compilers' register allocation colours an interference graph (variables live at the same time can't share a register). Exam timetabling and frequency assignment are the same problem.
Trees as mathematical objects
A tree is a connected graph with no cycles. For a graph with n vertices, these are all equivalent (any two imply the third):
- It is connected.
- It has no cycles.
- It has exactly n − 1 edges.
Further facts:
- There is exactly one path between any two vertices.
- Removing any edge disconnects the tree, and adding any edge creates exactly one cycle. That's why Kruskal adds V − 1 edges and why union-find detects the cycle-making edge.
- A binary tree of height h has at most 2^(h+1) − 1 nodes, so a binary tree with n nodes has height at least ⌊log₂ n⌋. That's the lower bound balanced trees achieve.
- A full binary tree with i internal nodes has i + 1 leaves (provable by structural induction, as above).
- Cayley's formula: there are nⁿ⁻² distinct labelled trees on n vertices.
- The number of binary trees with n nodes is the Catalan number Cₙ = C(2n, n)/(n+1): 1, 1, 2, 5, 14, 42, … Catalan numbers also count balanced parenthesis strings of length 2n and the ways to triangulate a polygon. They turn up surprisingly often in algorithm analysis.
Probability foundations
Sample spaces, events and axioms
Probability measures uncertainty. A sample space Ω is the set of all possible outcomes (two dice give 36 ordered outcomes). An event is a subset of outcomes ("sum is 7" = {(1,6), (2,5), …, (6,1)}). A probability P assigns each event a number with three axioms (Kolmogorov):
- 0 ≤ P(A) ≤ 1.
- P(Ω) = 1.
- For disjoint events, P(A ∪ B) = P(A) + P(B).
Everything else follows. With equally likely outcomes, P(A) = |A| / |Ω|, so probability becomes counting, which is why combinatorics comes first. P(sum = 7) = 6/36 = 1/6.
Derived rules:
- Complement: P(not A) = 1 − P(A). This is often the easiest route ("at least one" = 1 − "none").
- Union: P(A ∪ B) = P(A) + P(B) − P(A ∩ B) (inclusion–exclusion again).
- Union bound: P(A₁ ∪ … ∪ Aₙ) ≤ Σ P(Aᵢ). It's crude but always true, and very useful for "the probability that anything goes wrong."
Conditional probability, independence and Bayes
Conditional probability is the probability of A given that B happened: P(A | B) = P(A ∩ B) / P(B). Events are independent if P(A ∩ B) = P(A)·P(B), meaning knowing one tells you nothing about the other.
Bayes' theorem reverses conditioning:
P(A | B) = P(B | A) · P(A) / P(B)
The classic lesson: a test for a condition affecting 1% of people is 99% accurate (99% true positive rate, 1% false positive rate). If you test positive, what's the chance you have it?
P(pos) = 0.99·0.01 + 0.01·0.99 = 0.0198
P(sick | pos) = 0.99·0.01 / 0.0198 = 0.5 → only 50%, not 99%
When the base rate is low, most positives are false positives. The same maths explains why an alert that's "99% accurate" on a rare failure mode pages you mostly for nothing, and why spam filters (naive Bayes classifiers) multiply many weak signals together.
Independence in reliability. If each of 3 replicas fails independently with probability 0.01, all three fail together with probability 10⁻⁶. But failures are often correlated: the same rack, the same bad deploy, the same leap-second bug. Real availability is much worse than the independence calculation, a theme Part IX returns to.
Random variables and expectation
A random variable X maps outcomes to numbers (the sum of two dice, the latency of a request, the number of collisions). Its expected value is the probability-weighted average:
E[X] = Σ x · P(X = x) E[one die] = (1+2+3+4+5+6)/6 = 3.5
Linearity of expectation says E[X + Y] = E[X] + E[Y] always, even if X and Y are dependent. It's the single most useful tool in analysing randomised algorithms. Example: the expected number of collisions when hashing n keys into m buckets. Let Xᵢⱼ = 1 if keys i and j collide. Then E[Xᵢⱼ] = 1/m, and summing over C(n, 2) pairs gives E[collisions] = n(n−1)/(2m). With n = m that's about n/2 colliding pairs, which is why load factor matters.
Variance Var(X) = E[(X − E[X])²] measures spread. The standard deviation is √Var. For latency, the average hides the problem. That's why SLOs use percentiles (p50, p99, p99.9), covered in Part IX.
Common distributions:
| Distribution | Models | Mean | Engineering example |
|---|---|---|---|
| Bernoulli(p) | One yes/no trial | p | One request fails |
| Binomial(n, p) | Successes in n trials | np | Failures among n requests |
| Geometric(p) | Trials until first success | 1/p | Retries until success; probing length in hash tables |
| Uniform | Equally likely values | (a+b)/2 | Random jitter in backoff |
| Poisson(λ) | Count of rare events per interval | λ | Requests per second arriving independently |
| Exponential(λ) | Time between Poisson events | 1/λ | Inter-arrival times; queueing theory (Part IX) |
| Normal | Sums of many small effects | μ | Measurement noise (but latency is not normal: it's long-tailed) |
The birthday paradox and hash collisions
How many random values from a space of size N do you need before two collide with probability about 50%? Not N/2, but about 1.18 √N:
P(no collision among k) = (1 − 1/N)(1 − 2/N)…(1 − (k−1)/N) ≈ e^(−k²/2N)
→ P(collision) ≈ 50% when k ≈ √(2N ln 2) ≈ 1.18 √N
With N = 365 that gives k ≈ 23. Applied to engineering:
| ID or hash size | N | ~50% collision after |
|---|---|---|
| 32-bit | 4.3 × 10⁹ | ~77,000 values |
| 64-bit | 1.8 × 10¹⁹ | ~5 × 10⁹ values |
| 122 random bits (UUIDv4) | 5.3 × 10³⁶ | ~2.7 × 10¹⁸ values |
| 128-bit | 3.4 × 10³⁸ | ~2 × 10¹⁹ values |
| 256-bit (SHA-256) | 1.2 × 10⁷⁷ | ~4 × 10³⁸ values |
A 32-bit random ID collides after only tens of thousands of records. That's why random identifiers should be at least 64 bits, and usually 122–128 bits. It's also why a cryptographic hash needs 2× the bits of the security level you want: birthday attacks find collisions in √N work.
Recurrence relations
Writing recurrences
A recurrence defines a sequence in terms of earlier terms. Fibonacci is F(n) = F(n−1) + F(n−2) with F(0) = 0 and F(1) = 1. In algorithms, recurrences describe the running time of recursive code:
| Algorithm | Recurrence | Solution |
|---|---|---|
| Binary search | T(n) = T(n/2) + O(1) | O(log n) |
| Merge sort | T(n) = 2T(n/2) + O(n) | O(n log n) |
| Quicksort, worst case | T(n) = T(n−1) + O(n) | O(n²) |
| Naive Fibonacci | T(n) = T(n−1) + T(n−2) + O(1) | O(φⁿ) |
| Tree traversal | T(n) = 2T(n/2) + O(1) | O(n) |
| Karatsuba | T(n) = 3T(n/2) + O(n) | O(n^log₂3) ≈ O(n^1.585) |
| Tower of Hanoi | T(n) = 2T(n−1) + 1 | 2ⁿ − 1 moves |
Solving recurrences
1. Unrolling (iteration). Expand until you see the pattern:
T(n) = 2T(n−1) + 1
= 2(2T(n−2) + 1) + 1 = 4T(n−2) + 3
= 8T(n−3) + 7
= 2ᵏ T(n−k) + (2ᵏ − 1) → with T(0) = 0 and k = n: T(n) = 2ⁿ − 1
2. Recursion tree. Sum the work level by level. For T(n) = 2T(n/2) + cn: level i has 2ⁱ nodes each doing c·n/2ⁱ work, which is cn per level, over log₂ n levels. Total: cn log n.
3. Substitution. Guess the answer, then prove it by induction. For example, guess T(n) ≤ c·n log n for merge sort and verify the inductive step.
4. The master theorem (from chapter 4) for T(n) = a·T(n/b) + f(n). Compare f(n) with the "leaf work" n^(log_b a):
- f smaller (polynomially) → the leaves dominate → Θ(n^(log_b a)).
- f equal → each level costs the same → Θ(n^(log_b a) · log n).
- f larger, and regular → the root dominates → Θ(f(n)).
The intuition is the recursion tree. The tree has a^(log_b n) = n^(log_b a) leaves, and the master theorem just asks whether the work is concentrated at the top, the bottom, or spread evenly.
5. Characteristic equations for linear recurrences with constant coefficients. For F(n) = F(n−1) + F(n−2), try F(n) = rⁿ: r² = r + 1, so r = (1 ± √5)/2. The general solution is F(n) = α·φⁿ + β·ψⁿ with φ ≈ 1.618. Fitting the initial conditions gives Binet's formula: F(n) = (φⁿ − ψⁿ)/√5. So Fibonacci numbers grow exponentially, and F(n) has about 0.694n bits, which is why fib(94) overflows a u64.
// Linear recurrences can also be solved in O(log n) with matrix exponentiation:
// [F(n+1) F(n); F(n) F(n-1)] = [1 1; 1 0]^n
fn fib_matrix(n: u64) -> u64 {
type M = [[u64; 2]; 2];
fn mul(a: M, b: M) -> M {
[[a[0][0]*b[0][0] + a[0][1]*b[1][0], a[0][0]*b[0][1] + a[0][1]*b[1][1]],
[a[1][0]*b[0][0] + a[1][1]*b[1][0], a[1][0]*b[0][1] + a[1][1]*b[1][1]]]
}
let (mut result, mut base, mut e): (M, M, u64) = ([[1, 0], [0, 1]], [[1, 1], [1, 0]], n);
while e > 0 { // exponentiation by squaring (chapter 4)
if e & 1 == 1 { result = mul(result, base); }
base = mul(base, base);
e >>= 1;
}
result[0][1]
}
Boolean algebra
Boolean values and operations
Boolean algebra (George Boole, 1847) is the algebra of two values, written 0/1 or false/true, with the operations AND (·), OR (+) and NOT (an overbar or ′). Claude Shannon showed in his 1937 master's thesis that relay circuits implement Boolean algebra exactly. That is the foundation of every digital computer.
The laws (each has a dual, made by swapping AND ↔ OR and 0 ↔ 1):
| Law | AND form | OR form |
|---|---|---|
| Identity | x · 1 = x | x + 0 = x |
| Null (annihilator) | x · 0 = 0 | x + 1 = 1 |
| Idempotent | x · x = x | x + x = x |
| Complement | x · x′ = 0 | x + x′ = 1 |
| Commutative | x · y = y · x | x + y = y + x |
| Associative | (x·y)·z = x·(y·z) | (x+y)+z = x+(y+z) |
| Distributive | x·(y+z) = x·y + x·z | x + y·z = (x+y)·(x+z) |
| Absorption | x·(x+y) = x | x + x·y = x |
| De Morgan | (x·y)′ = x′ + y′ | (x+y)′ = x′ · y′ |
Note the second distributive law, x + y·z = (x+y)·(x+z). It's false in ordinary arithmetic but true here.
Normal forms
Every Boolean function can be written in a standard form read straight off its truth table:
- Sum of products (SOP / DNF): OR together one AND term (a minterm) for each row where the output is 1.
- Product of sums (POS / CNF): AND together one OR clause (a maxterm) for each row where the output is 0. SAT solvers take CNF as input.
Example: XOR, which is 1 when exactly one input is 1.
x y │ x⊕y SOP: x⊕y = x′·y + x·y′
0 0 │ 0 POS: x⊕y = (x + y) · (x′ + y′)
0 1 │ 1
1 0 │ 1
1 1 │ 0
Simplification reduces the number of gates (hardware) or conditions (software). Use algebraic laws, Karnaugh maps (a visual grid for up to 4–6 variables, grouping adjacent 1s), or algorithms like Quine–McCluskey and Espresso for larger functions.
Logic gates and functional completeness
Boolean operations are built in hardware as gates, made from transistors. Chapter 7 builds a CPU's ALU from them.
AND: 1 only if both 1 OR: 1 if either 1 NOT: inverts
NAND: NOT(AND) NOR: NOT(OR) XOR: 1 if inputs differ
NAND alone is functionally complete: every Boolean function can be built from NAND gates only. NOT x = x NAND x, AND = NOT(NAND), and OR(x, y) = (NOT x) NAND (NOT y). NOR is also complete. Real chips are built largely from NAND and NOR cells because they're the cheapest gates in CMOS.
A half adder adds two bits: sum = x ⊕ y and carry = x · y. A full adder also takes a carry in. Chaining 64 full adders (with carry-lookahead to make it fast) gives the 64-bit adder in your CPU. Chapter 6 shows how the same adder also performs subtraction thanks to two's complement.
Boolean algebra in software
The same algebra shows up all over software:
- Bit manipulation (chapter 6): masks, flags,
x & (x − 1)clears the lowest set bit, and XOR swaps and checksums. - Short-circuit evaluation:
a && bdoesn't evaluate b if a is false. Boolean algebra treats AND as commutative, but in code the order matters when the operands have side effects or can fail (p != null && p.x > 0). - SQL three-valued logic: SQL adds a third value, UNKNOWN (from NULL).
NULL = NULLis UNKNOWN, not TRUE, andWHERE x <> 5silently excludes rows where x is NULL. De Morgan still holds, but the law of the excluded middle (x OR NOT x = TRUE) doesn't. This is one of the most common SQL bug sources (chapter 56). - Query optimisation: databases rewrite predicates with these laws, for example pushing
NOTinward, factoring common terms, and converting to CNF to match indexes. - Feature flags and access rules: complex permission expressions are Boolean formulas. Simplify them, test them with truth tables, or verify them with a SAT/SMT solver.
- Bloom filters, bitmaps and bitsets: set algebra implemented with bitwise AND, OR and NOT.
Lab: discrete mathematics at work
Discrete mathematics shows up in engineering as estimates you can trust and arguments you can check. Each experiment here pairs a formula from this chapter with a simulation or exhaustive check (CPython 3.13), so you can see the mathematics predict the machine.
The birthday bound: how big must an identifier be?
With N possible values and n items drawn uniformly at random, the probability that some two collide is about 1 − e^(−n(n−1)/2N), reaching 50% near n ≈ 1.18·√N: far sooner than intuition expects. Formula against simulation:
def p_collision(n, space): return 1 - math.exp(-n * (n - 1) / (2 * space))
def simulate(n, bits, trials=2000):
hits = 0
for _ in range(trials):
seen = set()
for _ in range(n):
x = random.getrandbits(bits)
if x in seen: hits += 1; break
seen.add(x)
return hits / trials
300 random 16-bit ids: formula 49.6% simulated 48.6%
77,000 random 32-bit ids: formula 49.9% simulated 49.2%
10,000 random 32-bit ids: formula 1.2% simulated 1.6%
50% collision point ≈ 1.1774·√N: 32-bit → 77,162 ids; 64-bit → 5,056,894,494; 122-bit UUIDv4 → 2.71e+18
UUIDv4: generating 1 billion per second for a year gives collision probability ≈ 9.3e-05
A 32-bit random id (4 billion values) has a coin-flip chance of collision after only 77,000 ids, and a 1% chance after 10,000. That's why random identifiers are 64 bits at minimum and usually 122–128 (UUIDv4's 122 random bits survive a billion ids per second for a year with about a 1-in-10,000 chance of any collision). The same mathematics sets hash-table and Bloom-filter sizes (chapter 3), explains why 64-bit hash fingerprints are fine for deduplication of millions of items but not billions, and why a hash function's security is roughly half its output bits against collision attacks (a 128-bit hash gives 64-bit collision resistance).
The pigeonhole principle gives the hard limit: hash more than 2³² distinct strings into 32 bits and a collision is certain, not just likely.
Independence is an assumption, and usually false
The formula for "at least one of three replicas is up", each 99% available, is 1 − 0.01³ = 99.9999%, valid only if failures are independent. A simulation with and without a small shared cause (same rack, same region, the same bad deploy rolled to all three):
def system_up_independent():
return any(random.random() > 0.01 for _ in range(3)) # up if any replica is up
def system_up_correlated(p_shared=0.005):
if random.random() < p_shared: return False # shared cause takes all down
return any(random.random() > 0.005 for _ in range(3)) # remaining independent failures
formula assuming independence: 1 - 0.01^3 = 0.999999 (0.5 min/year down)
simulated, independent: 0.999997
simulated, 0.5% shared cause: 0.995180 (2,533 min/year down)
(The independent simulation's 0.999997 vs 0.999999 is sampling noise: a million trials see only a handful of triple failures.) Each replica is still about 99% available in the correlated case, yet the system goes from half a minute of downtime a year to 42 hours: the shared cause dominates everything. Multiplying probabilities is the most common mathematical error in reliability estimates, and it's why the engineering response is to remove shared causes (spread across zones, stagger deploys, use different failure domains: Volume 16, ch. 188) rather than add more identical replicas.
Boolean algebra in code review
A refactor "simplifies" an access condition. Is it equivalent? With four inputs there are only 2⁴ = 16 cases, so check them all:
original = lambda paid, admin, locked, trial: (paid or trial) and not locked or admin
refactored = lambda paid, admin, locked, trial: not (locked and not admin) and (paid or trial) # "same thing, cleaner"
deMorgan = lambda paid, admin, locked, trial: (not locked or admin) and (paid or trial or admin)
refactored differs from original on 2 of 16 inputs [{'paid': False, 'admin': True, 'locked': False, 'trial': False}, {'paid': False, 'admin': True, 'locked': True, 'trial': False}]
de Morgan rewrite differs from original on 0 of 16 inputs []
The refactor locked out admins without a paid plan: in the original, or admin (lowest precedence) grants access unconditionally; the refactor applied the admin exemption only to the lock check. The correct rewrite follows from the laws: distribute or admin over the and, getting (paid or trial or admin) and (not locked or admin). Two habits follow: know operator precedence (and binds tighter than or in essentially every language), and for small conditions, exhaustively test the truth table; for larger ones, a SAT/SMT solver (Z3) checks equivalence of conditions with dozens of variables in milliseconds.
Invariants: induction you can execute
A loop invariant is an inductive proof: true before the loop (base case), preserved by each iteration (inductive step), and, combined with the exit condition, it implies the result. Writing the invariant as an assertion and testing it on generated inputs (property-based testing, Volume 11) turns the proof sketch into a check:
def lower_bound(a, target):
lo, hi = 0, len(a) # invariant: all a[:lo] < target, all a[hi:] >= target
while lo < hi:
assert all(x < target for x in a[:lo]) and all(x >= target for x in a[hi:])
mid = lo + (hi - lo) // 2
if a[mid] < target: lo = mid + 1
else: hi = mid
return lo # termination: hi - lo strictly decreases each iteration
@given(st.lists(st.integers(-50, 50)).map(sorted), st.integers(-60, 60))
def test_lower_bound(a, t):
i = lower_bound(a, t)
assert all(x < t for x in a[:i]) and all(x >= t for x in a[i:])
lower_bound: invariant and postcondition held on 100 generated cases
When lo == hi, the invariant says everything left of lo is smaller and everything from lo on is at least the target: exactly the definition of the insertion point. Termination needs a separate argument (a variant: hi − lo is a non-negative integer that strictly decreases), which is the well-ordering principle at work. Off-by-one errors in binary search are invariant errors: write the invariant first and the < vs <= and mid + 1 vs mid choices follow from it.
Recurrences, checked against reality
Merge sort's comparison count satisfies T(n) = 2T(n/2) + (n − 1), whose solution is about n·log₂n − n. No comparison sort can beat log₂(n!) comparisons in the worst case (a decision tree with n! leaves has that height; by Stirling, ≈ n·log₂n − 1.44n). Counting:
n comparisons n·log2(n) ratio lower bound log2(n!)
1024 8,953 10,240 0.874 8,769
16384 208,705 229,376 0.910 205,747
131072 2,062,735 2,228,224 0.926 2,039,137
1048576 19,645,648 20,971,520 0.937 19,458,756
The measured counts sit within 1% of the information-theoretic lower bound: merge sort is nearly optimal in comparisons, and the ratio to n·log₂n creeps towards 1 as the −n term becomes relatively smaller. Counting arguments like log₂(n!) tell you when to stop optimising an approach and change the model instead (counting sort and radix sort beat n log n by not comparing at all).
Revision sheet: discrete mathematics
Key ideas
- Sets and their operations (union, intersection, difference, complement, power set, Cartesian product) are the language of databases, types and specifications.
- A relation is a set of pairs; properties (reflexive, symmetric, transitive, antisymmetric) define equivalence relations (partitions) and partial orders (dependencies, versions).
- A function maps each input to exactly one output; injective (one-to-one), surjective (onto), bijective (both, so invertible). The pigeonhole principle follows: hashing n + 1 keys into n buckets forces a collision.
- Propositional logic: and, or, not, implication, equivalence; De Morgan's laws; predicate logic adds "for all" (∀) and "there exists" (∃), the language of preconditions and invariants.
- Proof techniques: direct, contrapositive, contradiction, cases, construction, and induction (ordinary and strong), the basis of reasoning about loops and recursion.
- Counting: product and sum rules, permutations n!/(n−k)!, combinations n!/(k!(n−k)!), inclusion–exclusion, binomial theorem.
- Graph theory: degree, paths, cycles, connectivity, trees (n vertices, n − 1 edges, no cycles), bipartite graphs, planarity and colouring.
- Probability: sample spaces, independence, conditional probability and Bayes' rule, expected value and its linearity, variance; the birthday paradox.
- Recurrences describe recursive cost; solve by unrolling, recursion trees or the master theorem.
- Boolean algebra is logic as algebra on 0 and 1, the basis of circuits and condition simplification.
Numbers to remember
- 2¹⁰ = 1,024; 2²⁰ ≈ 1 million; 2³² ≈ 4.3 billion; 2⁶⁴ ≈ 1.8 × 10¹⁹.
- Birthday paradox: with 23 people, P(shared birthday) ≈ 0.5; for a b-bit hash, collisions become likely around 2^(b/2) items (about 77,000 for 32 bits).
- C(n, 2) = n(n − 1)/2 pairs: 1,000 items have 499,500 pairs.
Pitfalls
- Reading "if A then B" as also meaning "if B then A" (the converse).
- Treating events as independent when they share a cause (correlated failures in one data centre).
- Induction without a base case, or a step that silently assumes something beyond n.
- Confusing permutations (order matters) with combinations.
- Base-rate neglect: a 99%-accurate test for a 1-in-1,000 condition is mostly false positives.
Glossary
- Cardinality: the number of elements in a set.
- Contrapositive: "if not B then not A", logically equivalent to "if A then B".
- Invariant: a property that stays true throughout a process.
- Expected value: the probability-weighted average outcome.
- Bijection: a one-to-one correspondence between two sets.
- DAG: directed acyclic graph.