The method
Many expectation questions describe a process that, after one step, is in a situation you have seen before. Name each situation a state, let be the expected remaining cost (steps, flips, money) from state , and condition on the next step:
With finitely many states and the target reachable from every state, this linear system has a unique solution. Three decisions make or break the setup:
- The states must carry exactly the memory that matters. For "three heads in a row" the state is the current run length, not the whole history.
- Count the step you just took. The term is the most common thing to forget.
- Check the boundary. Which states are absorbing, and is anything reachable that you did not define?
The same equations with and , give probabilities of hitting one target before another.
Worked example
k heads in a row
A fair coin is flipped until it shows heads in a row. Find the expected number of flips , and evaluate it for .
Show solutionHide solution
Direct states. Let be the expected remaining flips with a current run of heads. Then and
A slicker recursion. To get in a row you must first get in a row, taking flips on average. Then one more flip: heads (probability ) finishes; tails sends you back to the start, needing a fresh . So
Adding 2 to both sides, , so and
This gives , , . For a coin with heads probability the same argument gives ; for two heads in a row with that is , .
Patterns and overlaps
For a general pattern, the state is "the longest prefix of the pattern that the recent flips end with". After a mismatch you do not always return to zero: in HTHT, if you hold HTH and flip H, the recent flips HTHH still end in H, so you fall back to state 1, not 0. The automaton below handles this mechanically.
For a fair coin there is a shortcut (from a martingale argument, often told as gamblers betting on ABRACADABRA): the expected waiting time is
summing over every length at which the pattern's first symbols equal its last symbols. HHH overlaps itself at : . HHTT overlaps only at : . HTHT overlaps at and : . Patterns that overlap themselves take longer. Every length- pattern appears at a given position with probability , so all have the same long-run frequency; a self-overlapping pattern's occurrences come in clusters, and clustered occurrences with the same frequency mean longer gaps before the first one.
The general solver is short enough to write in an interview:
from fractions import Fraction
def expected_wait(pattern: str, p_heads=Fraction(1, 2)) -> Fraction:
"""Expected flips until the pattern (e.g. "HHT") first appears."""
n = len(pattern)
prob = {"H": p_heads, "T": 1 - p_heads}
def next_state(k, c):
# Longest prefix of the pattern that is a suffix of pattern[:k] + c.
s = pattern[:k] + c
while s and not pattern.startswith(s):
s = s[1:]
return len(s)
# Unknowns E_0..E_{n-1}; E_n = 0. Row k: E_k - sum P * E_next = 1.
A = [[Fraction(0)] * n + [Fraction(1)] for _ in range(n)]
for k in range(n):
A[k][k] += 1
for c in "HT":
j = next_state(k, c)
if j < n:
A[k][j] -= prob[c]
# Gauss-Jordan elimination with exact fractions.
for col in range(n):
piv = next(r for r in range(col, n) if A[r][col] != 0)
A[col], A[piv] = A[piv], A[col]
A[col] = [x / A[col][col] for x in A[col]]
for r in range(n):
if r != col and A[r][col] != 0:
f = A[r][col]
A[r] = [a - f * b for a, b in zip(A[r], A[col])]
return A[0][n]
for pat in ["H", "HH", "HHH", "HT", "HHTT", "HTHT"]:
print(pat, expected_wait(pat))
print("HH, p=1/3:", expected_wait("HH", Fraction(1, 3)))
Output:
H 2
HH 6
HHH 14
HT 4
HHTT 16
HTHT 20
HH, p=1/3: 12
Solving linear recurrences
On a line of states the system becomes a recurrence. The standard one is a walk that steps up with probability and down with , stopping at or . The expected duration from satisfies
Solve it like a linear ODE: general homogeneous solution plus one particular solution, then fit the boundary conditions.
- Homogeneous part. Try in : , with roots and . So .
- Particular part. The constant forcing needs a particular solution; constants are already homogeneous, so try . Substituting gives .
- Repeated root. When both roots are 1, so the homogeneous part is and the particular solution must be quadratic: . With the boundaries, .
For , fitting gives
The fraction is the probability of reaching , so the formula is Wald's identity rearranged, with .
Worked example
how long does a favourable game last?
You start with $2, bet $1 at a time and win each bet with probability , stopping at $5 or $0. What is the expected number of bets?
Show solutionHide solution
Here , , , , , . The probability of reaching $5 is
Then
Check with Wald. The final wealth is 5 with probability and 0 otherwise, so the expected gain is . Each bet gains on average, so . Solving the four-equation system directly gives the same value, and .
Worked example
a walk with a reflecting floor
A walk starts at 0. From 0 it always moves to 1; from any it moves up or down by 1 with probability each. What is the expected time to first reach ?
Show solutionHide solution
Use differences instead of positions. Let be the expected time to go from to for the first time. Then the answer is , because to reach you must pass through every level in order.
From 0 the walk moves up at once, so . From , take one step: up (done), or down, after which you need to return to and then a fresh :
So , and
This is the diffusive scaling again: covering distance takes time of order . A simulation with averages about steps.
Second moments by the same method
Recurrences work for too: condition on the first step and expand the square. For a geometric number of trials with success probability , the first trial succeeds (so ) or fails (so with an independent copy):
With this gives and . For a die waiting for a 6, and : the standard deviation, about 5.5, is almost as large as the mean.
Knowledge check
A fair die is rolled until a 5 is immediately followed by a 6. What is the expected number of rolls?
Knowledge check
A walk starts at 0, always steps to 1 from 0, and otherwise moves ±1 with equal probability. What is the expected time to first reach 10?
Knowledge check
A fair die is rolled until the first 6. Given that every roll was even (including the 6), what is the expected number of rolls?
Key takeaways
- Define states that carry exactly the relevant memory, write , and set the target to 0.
- Build big waits from small ones: gives for heads in a row.
- Fair-coin pattern waits are the sum of over the self-overlap lengths ; a short exact solver handles any pattern and any bias.
- Solve line recurrences as homogeneous plus particular solution; a repeated root 1 forces polynomial particular solutions such as .
- Expected passage times split into level-by-level differences; the reflecting walk takes steps to reach .
- Second moments follow from the same first-step conditioning; check answers with Wald or a symmetry argument when you can.
Practice problems
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).