Expectation & the linearity trick
Random variables & moments defined expectation and stated its one superpower: linearity, with no independence required. This chapter is the deep dive on that superpower — the single most productive computational idea in probability. The method is three steps long: decompose a count into indicators, take expectations, add. It computes in one line what distributions take pages to describe — hat-check matches, birthday collisions, records, runs, coupon collections — and it extends to second moments and to a tail-sum formula that reads means off survival curves. By the end you should reach for indicators reflexivelywhenever a question begins “what is the expected number of…”.
Most operations in probability fight you: the distribution of a sum is a convolution, the maximum of two variables has a new CDF, dependence tangles every joint computation. Expectation is the exception — it slides through sums untouched, whatever the dependence between the pieces. So the winning move is to rewrite your quantity as a sum of the simplest possible pieces — indicators, which are events wearing a 0/1 costume. A complicated random count is a pile of tiny yes/no questions, and the expected count is the sum of their yes-probabilities. You never need to know how the answers correlate — until you ask about spread or tails, when the correlations come storming back (the closing warning below).
Centre of mass, fair price#
Two pictures of are worth keeping, beyond the defining formula in random variables & moments. First, centre of mass: place weight at each point , and is where the line balances. Balance points respond linearly to shifting and scaling the masses — why linearity should feel inevitable — and they chase outliers: a tiny mass placed far out moves the balance point a long way, the geometric seed of every fat-tail pathology in LLN & CLT.
Second, fair price: is the unique price at which a ticket paying the random amount is a break-even trade in the long run — charge more and the seller wins on average, less and the buyer does. This is the sense in which expectation prices a gamble with a single number, and it is the licence behind every expectancy computation on a trading desk: a strategy’s worth per trade is , full stop (the math of edge). The caveats — infinite means, and the fact that a fair price says nothing about the ride — are refinements; the fair-price reading is the anchor.
Linearity: the theorem that asks for nothing#
For any random variables with finite means and any constants :
No independence. No identical distributions. No assumptions about the joint behaviour at all. The proof (given in full in random variables & moments) is one rearrangement: write the expectation of the sum against the joint distribution, split the sum, and observe that each term only ever consults its own marginal — the joint distribution, where all the dependence lives, gets summed out before it can matter.
Every other summary of a sum depends on the dependence: needs the covariance, the distribution of needs the entire joint law, and both move when correlation moves. The mean of a sum alone is immune, and that immunity makes the indicator method a method: carve a count into overlapping, entangled, perfectly correlated pieces — however the problem makes convenient — and the expected total still adds up. When a computation feels blocked because “the events aren’t independent,” that instinct is the bug: for expectations, dependence is never an obstruction.
The indicator method, as a recipe#
An indicator equals 1 when occurs and 0 otherwise, so — expectations of indicators are probabilities. The recipe:
- Step 1 — decompose. Recognise your quantity as a count and write , where = “the -th potential contributor actually contributes.”
- Step 2 — take expectations. Linearity: — each a one-event probability, usually easy, often by symmetry.
- Step 3 — sum. Frequently all are equal and the answer is .
The craft is entirely in Step 1: choosing what to index — items (fixed points), pairs (collisions, inversions), positions (records, runs, patterns), boxes (empty cells), or stages of a process (coupon collector). Everything after that choice is arithmetic.
Five classics, fully worked#
people leave hats at a party; the hats come back in uniformly random order. Expected number of correct returns? Index the people: = “person gets hat .” Hat is equally likely to land on any of the heads, so and
One expected match whether or a million — a surprising invariance, delivered without touching the ferociously dependent joint structure (person 1 matching changes everyone else’s chances). Contrast the distributional question “what is ?” — the derangement problem, which needs full inclusion–exclusion (counting & combinatorics) to reach .
people, 365 equally likely birthdays. Expected number of pairs sharing a birthday? Index the pairs: of them, each sharing with probability (whatever the first person’s birthday, the second matches it with probability ):
At : — crossing exactly where the birthday probability crosses . No coincidence: for rare, roughly independent events, — the heuristic developed in balls, bins & birthdays.
Observe i.i.d. continuous values (no ties); position sets a record if it exceeds everything before it. By symmetry each of the first values is equally likely to be their largest, so and
A century of daily data () should produce only record highs under the i.i.d. null — records are logarithmically rare. The indicators are dependent and non-identically distributed; linearity does not blink.
Flip a fair coin times; a run is a maximal block of equal outcomes (HHTHH has runs HH, T, HH). Index the boundaries: a new run starts at flip 1, and at flip exactly when it differs from flip — probability :
100 flips: 50.5 runs expected. Eyeballed randomness looks streaky — a “hot regime” narrative fits almost any fair sequence — and comparing observed runs to is precisely the runs test for serial dependence.
And a preview: throw balls into boxes uniformly. Indexing the boxes, each is empty with probability , so the expected number of empty boxes is — the opening move of the occupancy theory in balls, bins & birthdays.
Operational questions on a desk are expected-count questions, and linearity answers them without a correlation model: expected positions hitting stops today = sum of per-position stop probabilities; expected strategies in a 200-strategy scan clearing a Sharpe threshold by luck = 200 × (false positive rate) — the arithmetic of multiple testing & paradoxes. All exact under arbitrary dependence. What dependence changes is the distribution aroundthe count: correlated stops fire together, so a mean of 5 stop-outs can mean “5 most days” or “0 most days, 50 in a crash.” Means for free, tails at a price.
Coupon collector, by stage decomposition#
Indicators decompose counts; the same linearity decomposes durations. How many uniform draws from coupon types until you own all ? Stage begins when you hold distinct types and ends when a new one arrives; during it each draw is new with probability , so the stage length is geometric with mean , and linearity glues the stages:
For : draws to see every card. The stage lengths happen to be independent, but the proof never used that — only that the total is a sum of stages with known means. The harder cousins (unequal coupon probabilities, collect two of each) live in probability brainteasers; stage decomposition is the move that opens all of them.
The tail-sum formula#
For a non-negative integer-valued , the mean can be read off the survival function — no PMF required:
The formula is the indicator method applied to thresholds: clears exactly of the thresholds , so . Take expectations — linearity is safe for non-negative terms — and each indicator surrenders its probability:
The picture is a double count: stack a bar of height with mass ; summing bar by bar gives , summing layer by layer gives — same area, two slicings. The continuous version is the same swap with Fubini: the mean is the area under the survival curve.
Two showcase uses. The geometric: , so — two lines, no power-series differentiation. Better still, the expected maximum of fair dice, where the survival form is natural because maxima have easy CDFs: , so
For : ; for , . Whenever is easier than — maxima, waiting times, survival processes — the tail-sum route wins; it is also the identity that finishes Wald’s theorem in martingales & optional stopping.
Second moments: the method extends to pairs#
Squaring a sum of indicators produces indicator pairs, and — linearity reaches second moments too:
The diagonal terms reproduce (indicators square to themselves); the off-diagonal terms need pairwisejoint probabilities — dependence’s first, limited, appearance, and still far less than the full joint law.
For the hat-check : , and for , (hat home, then hat home among the remaining ). With diagonal and off-diagonal terms:
Mean 1, variance 1, for every — and in the limit the count converges to Poisson(1): , about 36.8% chance of no match, 36.8% of exactly one, 18.4% of two (Poisson processes).

Symmetry × linearity: expected positions#
The most elegant applications pair linearity with a symmetry argument that makes every obvious. The canonical example: in a shuffled 52-card deck, how many cards come before the first ace, on average?
Index the 48 non-aces: = “non-ace lies before all four aces.” The relative order of five specific cards — non-ace and the four aces — is uniform over the arrangements, so non-ace comes first with probability . Hence
and the first ace sits at expected position . The equivalent picture: the four aces split the other 48 cards into 5 exchangeable gaps, each holding cards on average. Spacing arguments of this kind are developed properly in symmetry & exchangeability and order statistics.
Simulation check#
Two headline results — hat-check mean and variance both exactly 1, and records growing like — verified against theory. Simulation is the honest referee for indicator arguments: if your decomposition double-counts or your symmetry claim is wrong, ten lines of numpy say so immediately.
import numpy as np
rng = np.random.default_rng(7)
trials = 200_000
n = 52
# 1) Hat-check: fixed points of a random permutation of 52 items
perms = np.argsort(rng.random((trials, n)), axis=1)
matches = (perms == np.arange(n)).sum(axis=1)
print(f"E[matches] = {matches.mean():.4f} (theory 1, for every n)")
print(f"Var[matches] = {matches.var():.4f} (theory 1)")
# distribution vs Poisson(1): the mean was one line, this took a limit theorem
from math import e, factorial
for k in range(4):
emp, thy = (matches == k).mean(), e**-1 / factorial(k)
print(f" P(X = {k}) = {emp:.4f} (Poisson(1): {thy:.4f})")
# 2) Records in an i.i.d. sequence of length 52: E = H_52
x = rng.random((trials, n))
records = (x == np.maximum.accumulate(x, axis=1)).sum(axis=1)
H_n = (1 / np.arange(1, n + 1)).sum()
print(f"E[records] = {records.mean():.4f} (theory H_52 = {H_n:.4f})")Two random variables with mean 1 can behave arbitrarily differently: the hat-check count is Poisson(1)-like and essentially never exceeds 5; a variable equal to 1000 with probability and 0 otherwise also has mean 1 and is a lottery ticket. Linearity cannot tell them apart. An indicator computation licenses sentences about averages(“one match expected”), never about probabilities(“a match is likely”) — converting means and second moments into tail control is exactly the job of Markov, Chebyshev, and Chernoff in inequalities & tail bounds. In markets the distinction is the whole job: two books with identical expectancy can carry utterly different ruin probabilities, and confusing the mean for the distribution is how positive-expectancy traders go broke — see position sizing.
Practice problems#
Five problems that test the method — attempt each before reading the solution; choosing what to index is the whole exercise.
A standard 52-card deck (26 red, 26 black) is shuffled. What is the expected number of adjacent pairs of the same colour?
Solution. Index the 51 adjacent positions: = “cards and share a colour.” Whatever card sits at position , 25 of the remaining 51 match its colour, so by exchangeability. Hence exactly. The events overlap and are negatively dependent through the colour counts — all irrelevant. Lesson: when symmetry makes the per-event probability uniform, the answer is (number of slots) × (one probability), and the messy dependence never enters.
Roll a fair die times. What is the expected number of distinct faces seen?
Solution. Index the six faces: = “face appears at least once.” The complement is clean: , so . Check the extremes: gives 1; gives — six rolls see barely four faces on average. The same identity with boxes and balls is the bootstrap’s “63.2% of observations appear in a resample” (resampling & bootstrap). Lesson: for “at least once” indicators, always pass through the complement.
In a uniformly random permutation of (), a position is a local maximum if its value exceeds its neighbours’ (one neighbour at the ends). Find the expected number of local maxima.
Solution. Index the positions. At an interior , each of the three values at is equally likely to be the largest: . At an endpoint, largest of two: . Therefore
For : . Roughly a third of any random sequence is a local peak — worth remembering when a chart’s “resistance levels” look plentiful. Adjacent indicators are strongly dependent (neighbouring peaks are impossible); the answer never noticed. Lesson: local questions need only local symmetry.
Flip a fair coin times. What is the expected number of times the pattern HT appears (in consecutive flips)? And how does HH compare?
Solution. Index the starting positions: , so . The same computation gives for HH — equal expected counts, even though the expected waiting time to the first HH is 6 flips versus 4 for HT (the overlap argument in martingales & optional stopping). No contradiction: HH occurrences arrive in clumps (HHH contains two), rarer to start but bunched when they come. Lesson: expected counts are insensitive to clustering; waiting times are made of it — the mean-versus-distribution warning in miniature.
An inversion is a pair whose values appear in decreasing order. Find the expected number of inversions of a uniformly random permutation of items.
Solution. Index the pairs. Each is inverted with probability exactly (swapping the two values is a bijection between inverted and non-inverted arrangements), so
A shuffled 52-card deck carries expected inversions — also the expected number of swaps bubble sort performs, and the centring constant of Kendall’s tau in regression & inference. Lesson: “count the pairs, halve by symmetry” is a complete proof — the two-element swap is the entire argument.
Next: with the machinery for means in hand, meet the named distributions it computes against: The distribution zoo.
