edgekit

Counting & combinatorics

Almost every discrete probability question reduces to counting: favourable outcomes over total outcomes, when outcomes are equally likely. This chapter builds the counting toolkit — the multiplication rule, permutations and combinations, the binomial theorem, stars and bars, inclusion–exclusion, derangements, and the symmetry arguments that turn pages of algebra into one-line answers. It closes with the birthday problem, the first of many places where a quiet exponential sneaks up on your intuition.

Intuition — why counting comes first

The classical definition of probability — for equally likely outcomes — makes probability literally a counting problem. Classic problems cluster in this territory because it has no formulas to hide behind: either you can decompose the outcome space cleanly or you cannot. The entire skill is choosing the right decomposition — ordered or unordered, with or without replacement, direct count or complement count — and the tools below are exactly that menu.

The multiplication rule and ordered selection#

The multiplication rule is the atom of counting: if a procedure has stages and stage can be completed in ways regardless of the earlier choices, the whole procedure has outcomes. Everything else in this chapter is this rule plus bookkeeping.

An ordered selection of distinct items from is a permutation. The first slot has choices, the second , and so on:

Worked example — arranging a watchlist

Display 3 of 8 instruments in ranked dashboard slots: arrangements. Rank all 8 and it is — factorials explode, which is why brute-force enumeration dies fast and clever counting matters.

Combinations and the binomial theorem#

When order does not matter, we are counting combinations — subsets of size . The derivation is a deliberate overcount-then-divide: each unordered subset of size appears exactly times among the ordered selections (once per internal ordering), so

Two identities do most of the work in practice. Symmetry, , because choosing which to include is the same as choosing which to exclude. And Pascal’s identity:

Proof — Pascal's identity by conditioning on one element

Fix a particular element, say item . Every size- subset either contains it or not. Subsets that contain it are completed by choosing of the remaining : ways. Subsets that avoid it choose all from the other : ways. The two cases are disjoint and exhaustive, so they add. This “condition on one element” move is a template — the same trick proves many binomial identities without algebra.

Pascal's triangle with binomial coefficients, highlighting how each entry is the sum of the two above it
Pascal's triangle: row n lists C(n,0) … C(n,n), and each entry is the sum of the two above it — Pascal's identity made visual. The rows also sum to 2^n (every subset is in or out) and, normalised, converge to the binomial distribution's bell shape.

The binomial theorem is the algebraic face of the same count:

Proof sketch — binomial theorem by choosing factors

Expand as a product of brackets. Each term in the expansion picks either or from every bracket, so a term equal to arises once for every choice of which brackets contribute the — and there are exactly such choices. Setting gives (every element in or out), and shows binomial probabilities sum to 1 — the distribution you will meet properly in the distribution zoo.

Worked example — committee counts by hand

From 12 analysts, how many ways to form a research pod of 4? . If the pod must contain exactly 2 of the 5 seniors (and so 2 of the 7 juniors), count each group independently and multiply: . The multiplication rule glues independent sub-counts together.

Stars and bars#

How many ways can you place identical items into labelled boxes — equivalently, how many non-negative integer solutions has ? The answer:

Proof — the stars-and-bars bijection

Write the items as stars and insert bars to cut the row into segments; segment ’s star-count is . For example encodes . Every arrangement of stars and bars corresponds to exactly one solution and vice versa, and arranging them means choosing which of the positions hold bars: . For strictly positive solutions (), first give each box one star, leaving free: .

Worked example — allocating risk units

You have 10 identical 1R risk units to spread across 4 strategies (a strategy may get zero). Solutions of : allocations. Require every strategy to get at least one unit and it drops to . Which allocation is best is a sizing question (the math of edge); sizing the search space is where any grid search starts.

Inclusion–exclusion#

Unions are awkward because events overlap; inclusion–exclusion corrects the double counting. For two and three events:

and in general, for events :

Proof — two sets exactly, general case by counting an element

Two sets. Decompose the union into disjoint pieces: . Additivity over disjoint events gives . Since and similarly for , substituting yields .

General case (sketch). Take an outcome belonging to exactly of the events. On the left it is counted once. On the right it is counted times, and by the binomial theorem applied to this alternating sum equals exactly 1. Every outcome is counted once on both sides, so the identity holds.

Worked example — divisible by 2 or 3

How many integers in are divisible by 2 or 3? Multiples of 2: 50. Multiples of 3: 33. Multiples of 6 (counted twice): 16. Total: . Note the rhythm — add the singles, subtract the pairs — which scales mechanically to any number of conditions.

Truncating the alternating sum after the first term gives the union bound — proved properly in the axioms chapter and the engine behind Bonferroni corrections in multiple testing.

Derangements and the 1/e law#

A derangement is a permutation with no fixed point — people toss their hats in a pile, each takes one back at random, and nobody gets their own. Let count them. Inclusion–exclusion cracks this in three lines.

Proof — counting derangements, and the limit 1/e

Let be the event that person gets their own hat. We want the complement of . Any intersection of specific ’s fixes those hats and permutes the rest freely: permutations, and there are ways to pick which . So by inclusion–exclusion,

The sum is the partial Taylor series of , so

Convergence is astonishingly fast — the error is below . The chance that at least one person gets their own hat is — a constant worth memorising; it reappears as the chance an observation enters a bootstrap resample in resampling.

nD_nD_n / n!
320.3333
490.3750
62650.3681
101,334,9610.36788 (1/e to 5 dp)

Symmetry arguments#

The fastest counting is the counting you avoid. A symmetry argument notes that the random mechanism treats certain outcomes identically, so their probabilities must be equal — no enumeration needed.

  • Any position is as good as the first. Shuffle a deck: the probability the 17th card is an ace is , same as the first — the shuffle is exchangeable, so every position sees the same marginal distribution.
  • Relative order is uniform. Among distinct exchangeable draws, all orderings are equally likely — the germ of order statistics and of the fact that a record at time has probability .
  • Pair up outcomes.A random walk’s paths reflect into equally likely mirror paths — the reflection principle of random walks & Brownian motion is a symmetry argument in disguise.
Worked example — second ace, by symmetry

Deal two cards. What is ? The brute-force way conditions on the first card: . The symmetry way: the second card is a uniformly random card, so . Same answer, zero algebra. The best practice questions are deliberately set up so the conditional route is a slog and the symmetry route is one sentence.

The birthday problem#

Among people with uniformly random birthdays over 365 days, what is the chance two share a birthday? Count the complement — all birthdays distinct — with the multiplication rule:

Derivation — the exponential approximation

Take logs and use for small :

So the collision probability is approximately

Setting this to gives — hence the famous answer 23. The mechanism: the number of pairs grows like — with 23 people there are already chances to collide. Intuition tracks ; probability tracks . Exact values: at , by .

Probability of at least one shared birthday versus group size, crossing 50 percent near 23 people, with the exponential approximation overlaid
The birthday problem: exact collision probability (solid) against group size, with the 1 − exp(−n(n−1)/730) approximation (dashed) nearly on top of it. The curve crosses 1/2 at n = 23 and is nearly certain by 60 — pair counts grow quadratically, so collisions arrive far earlier than linear intuition expects.
Quant lens — backtest collisions and the combinatorics of overfitting

The birthday effect is the statistical heart of data snooping: test many strategy variants and the implicit comparisons grow combinatorially, so “surprising” coincidences become near-certain by chance. A grid of 5 entry rules × 6 exit rules × 10 lookbacks is already strategies by the multiplication rule; the expected maximum Sharpe among them grows like even when every strategy is pure noise. The counting above is how you size the search space you actually explored — the first number an honest backtest audit asks for, and the input to the corrections in multiple testing & paradoxes.

Simulation confirms both headline constants — the birthday collision at and the derangement law:

counting_checks.py
import numpy as np

rng = np.random.default_rng(11)
trials = 200_000

# --- Birthday problem: P(shared birthday) among n = 23 people ---
n = 23
bdays = rng.integers(0, 365, size=(trials, n))
s = np.sort(bdays, axis=1)
collide = (np.diff(s, axis=1) == 0).any(axis=1)
print(f"P(match), n=23:  {collide.mean():.4f}   (exact 0.5073)")

# --- Derangements: P(no fixed point) for a random permutation, n = 10 ---
m = 10
perms = np.argsort(rng.random((trials, m)), axis=1)   # uniform random permutations
no_fixed = ~(perms == np.arange(m)).any(axis=1)
print(f"P(derangement):  {no_fixed.mean():.4f}   (1/e = {1/np.e:.4f})")

Sampling with and without replacement#

The last distinction the toolkit needs: does a draw change the pool? Draw items from a population of containing “successes.”

  • With replacement — draws are independent, each a success with probability . The success count is binomial: .
  • Without replacement — draws deplete the pool and are dependent. The count is hypergeometric, a pure ratio of combination counts: — choose which successes, choose which failures, over all ways to choose the sample.

Both have mean , but the hypergeometric variance carries the finite-population correction — sampling without replacement is less variable, because each draw removes what you drew. When the correction vanishes and the two coincide. Both distributions get full treatment in the distribution zoo.

Worked example — at least one ace in a 5-card hand

Complement count: , so . The pattern — “at least one” means complement of “none” — is the single most-used move in counting problems.

Practice problems#

Six classics — note how often the slick answer is a complement, a symmetry, or a division by an overcount.

Problem 1 — Handshakes

At a meeting of people, everyone shakes hands with everyone else exactly once. How many handshakes? If there were 66 handshakes, how many people attended?

Solution. A handshake is an unordered pair of people: . (Slick double-count: each of people shakes hands, and each shake is counted twice — divide by 2.) For 66: , so . Notice this is the same that counts pairwise correlations in an -asset portfolio and pairwise collisions in the birthday problem.

Problem 2 — Splitting into two teams

How many ways can 10 people be split into two teams of 5?

Solution. The trap is . That counts labelledteams (“team A gets these five”) — but choosing five people for team A and choosing their five complements produce the same split. Each unlabelled split is counted twice, so the answer is . Generalisation worth stating aloud: unlabelled groups of give . Overcount-then-divide, again.

Problem 3 — De Méré's bet: at least one six

Which is more likely: at least one 6 in 4 rolls of a die, or at least one double-6 in 24 rolls of two dice?

Solution. Complements. , while . The first bet wins in the long run; the second loses — the discrepancy that sent de Méré to Pascal and Fermat. The naive intuition fails because probabilities of unions are not sums — inclusion–exclusion is exactly the ignored correction.

Problem 4 — The hat-check (derangement) problem

100 traders leave badges at reception; the receptionist hands them back uniformly at random. What is the probability nobody receives their own badge? What is the expected number who do?

Solution. From the derangement derivation above, — effectively exact at . For the expected number of matches, use indicators: with , so — exactly one match on average, for any , despite the dependence between indicators. That trick gets a full section in random variables & moments.

Problem 5 — Count the full houses

How many 5-card poker hands are a full house (three of one rank, two of another), and what is the probability?

Solution. Build the hand by stages with the multiplication rule: choose the trip rank (13), its three suits (), the pair rank (12 — order matters here because trip-rank and pair-rank play different roles), its two suits (): hands. Probability: , about 1 in 694. The classic error is using for the ranks — that treats trip-rank and pair-rank as interchangeable, and they are not: KKK-QQ and QQQ-KK are different hands.

Problem 6 — Birthday variants

(a) How many people are needed for a 50% chance someone shares your birthday? (b) Roughly how many for a 50% chance of a three-way birthday collision?

Solution. (a) This is not 23 — matching a fixed day kills the quadratic pair effect. ; setting it to gives . Ten times more people, because only comparisons are available rather than . (b) Triples scale as , each hitting with probability ; the count reaches coin-flip territory around (the exact answer). Say the takeaway out loud: what counts as a coincidence sets the exponent, and the exponent determines everything.

Next: counting handles equally likely outcomes; axioms, conditioning, and Bayes handle everything else. Axioms, conditioning & Bayes.