Skip to content
LeetQuant
F4 Random Variables and Expectation

F4 · Random Variables and Expectation · Lesson 8 of 8

Recurrences for Expectations

Set up and solve first-step equations: waiting times for patterns, expected game lengths, second moments, and linear recurrences with boundary conditions.

20 min

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 EsE_s be the expected remaining cost (steps, flips, money) from state ss, and condition on the next step:

Es=cs+∑s′P(s→s′) Es′,Etarget=0.E_s = c_s + \sum_{s'} P(s \to s')\,E_{s'}, \qquad E_{\text{target}} = 0 .

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:

  1. 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.
  2. Count the step you just took. The cs=1c_s = 1 term is the most common thing to forget.
  3. Check the boundary. Which states are absorbing, and is anything reachable that you did not define?

The same equations with cs=0c_s = 0 and Etarget=1E_{\text{target}} = 1, Eother end=0E_{\text{other end}} = 0 give probabilities of hitting one target before another.

Worked example

k heads in a row

A fair coin is flipped until it shows kk heads in a row. Find the expected number of flips TkT_k, and evaluate it for k=3k = 3.

Show solution

Direct states. Let EjE_j be the expected remaining flips with a current run of jj heads. Then Ek=0E_k = 0 and

Ej=1+12Ej+1+12E0,j=0,…,k−1.E_j = 1 + \tfrac12 E_{j+1} + \tfrac12 E_0, \qquad j = 0, \dots, k-1 .

A slicker recursion. To get kk in a row you must first get k−1k - 1 in a row, taking Tk−1T_{k-1} flips on average. Then one more flip: heads (probability 12\tfrac12) finishes; tails sends you back to the start, needing a fresh TkT_k. So

Tk=Tk−1+1+12Tk⟹Tk=2Tk−1+2,T0=0.T_k = T_{k-1} + 1 + \tfrac12 T_k \quad\Longrightarrow\quad T_k = 2T_{k-1} + 2, \qquad T_0 = 0 .

Adding 2 to both sides, Tk+2=2(Tk−1+2)T_k + 2 = 2(T_{k-1} + 2), so Tk+2=2k+1T_k + 2 = 2^{k+1} and

Tk=2k+1−2.T_k = 2^{k+1} - 2 .

This gives T1=2T_1 = 2, T2=6T_2 = 6, T3=14T_3 = 14. For a coin with heads probability pp the same argument gives Tk=(Tk−1+1)/pT_k = (T_{k-1} + 1)/p; for two heads in a row with p=13p = \tfrac13 that is T1=3T_1 = 3, T2=12T_2 = 12.

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

E[T]=∑1≤j≤nprefixj=suffixj2j,\mathbb{E}[T] = \sum_{\substack{1 \le j \le n \\ \text{prefix}_j = \text{suffix}_j}} 2^{j} ,

summing over every length jj at which the pattern's first jj symbols equal its last jj symbols. HHH overlaps itself at j=1,2,3j = 1, 2, 3: 2+4+8=142 + 4 + 8 = 14. HHTT overlaps only at j=4j = 4: 1616. HTHT overlaps at j=2j = 2 and 44: 4+16=204 + 16 = 20. Patterns that overlap themselves take longer. Every length-nn pattern appears at a given position with probability 2−n2^{-n}, 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 pp and down with q=1−pq = 1 - p, stopping at 00 or NN. The expected duration DkD_k from kk satisfies

Dk=1+p Dk+1+q Dk−1,D0=DN=0.D_k = 1 + p\,D_{k+1} + q\,D_{k-1}, \qquad D_0 = D_N = 0 .

Solve it like a linear ODE: general homogeneous solution plus one particular solution, then fit the boundary conditions.

  • Homogeneous part. Try Dk=rkD_k = r^k in Dk=pDk+1+qDk−1D_k = p D_{k+1} + q D_{k-1}: pr2−r+q=0p r^2 - r + q = 0, with roots r=1r = 1 and r=q/pr = q/p. So A+B(q/p)kA + B(q/p)^k.
  • Particular part. The constant forcing 11 needs a particular solution; constants are already homogeneous, so try CkCk. Substituting gives C=1/(q−p)C = 1/(q - p).
  • Repeated root. When p=q=12p = q = \tfrac12 both roots are 1, so the homogeneous part is A+BkA + Bk and the particular solution must be quadratic: −k2-k^2. With the boundaries, Dk=k(N−k)D_k = k(N - k).

For p≠qp \ne q, fitting D0=DN=0D_0 = D_N = 0 gives

Dk=kq−p−Nq−p⋅1−(q/p)k1−(q/p)N.D_k = \frac{k}{q - p} - \frac{N}{q - p} \cdot \frac{1 - (q/p)^k}{1 - (q/p)^N} .

The fraction is the probability PkP_k of reaching NN, so the formula is Wald's identity E[ST]−k=(p−q) E[T]\mathbb{E}[S_T] - k = (p - q)\,\mathbb{E}[T] rearranged, with E[ST]=NPk\mathbb{E}[S_T] = N P_k.

Worked example

how long does a favourable game last?

You start with $2, bet $1 at a time and win each bet with probability 23\tfrac23, stopping at $5 or $0. What is the expected number of bets?

Show solution

Here p=23p = \tfrac23, q=13q = \tfrac13, q−p=−13q - p = -\tfrac13, q/p=12q/p = \tfrac12, k=2k = 2, N=5N = 5. The probability of reaching $5 is

1−(1/2)21−(1/2)5=3/431/32=2431.\frac{1 - (1/2)^2}{1 - (1/2)^5} = \frac{3/4}{31/32} = \frac{24}{31} .

Then

D2=2−1/3−5−1/3⋅2431=−6+36031=17431≈5.61.D_2 = \frac{2}{-1/3} - \frac{5}{-1/3}\cdot\frac{24}{31} = -6 + \frac{360}{31} = \frac{174}{31} \approx 5.61 .

Check with Wald. The final wealth is 5 with probability 2431\tfrac{24}{31} and 0 otherwise, so the expected gain is 5⋅2431−2=58315 \cdot \tfrac{24}{31} - 2 = \tfrac{58}{31}. Each bet gains 13\tfrac13 on average, so E[T]=5831/13=17431\mathbb{E}[T] = \tfrac{58}{31} \big/ \tfrac13 = \tfrac{174}{31}. Solving the four-equation system directly gives the same value, and D1,D2,D3,D4=14731,17431,14131,7831D_1, D_2, D_3, D_4 = \tfrac{147}{31}, \tfrac{174}{31}, \tfrac{141}{31}, \tfrac{78}{31}.

Worked example

a walk with a reflecting floor

A walk starts at 0. From 0 it always moves to 1; from any k≥1k \ge 1 it moves up or down by 1 with probability 12\tfrac12 each. What is the expected time to first reach nn?

Show solution

Use differences instead of positions. Let dkd_k be the expected time to go from kk to k+1k + 1 for the first time. Then the answer is d0+d1+⋯+dn−1d_0 + d_1 + \dots + d_{n-1}, because to reach nn you must pass through every level in order.

From 0 the walk moves up at once, so d0=1d_0 = 1. From k≥1k \ge 1, take one step: up (done), or down, after which you need dk−1d_{k-1} to return to kk and then a fresh dkd_k:

dk=1+12⋅0+12 (dk−1+dk)⟹dk=dk−1+2.d_k = 1 + \tfrac12 \cdot 0 + \tfrac12\,(d_{k-1} + d_k) \quad\Longrightarrow\quad d_k = d_{k-1} + 2 .

So dk=2k+1d_k = 2k + 1, and

E[Tn]=∑k=0n−1(2k+1)=n2.\mathbb{E}[T_n] = \sum_{k=0}^{n-1} (2k + 1) = n^2 .

This is the diffusive scaling again: covering distance nn takes time of order n2n^2. A simulation with n=10n = 10 averages about 100100 steps.

Second moments by the same method

Recurrences work for E[T2]\mathbb{E}[T^2] too: condition on the first step and expand the square. For a geometric number of trials NN with success probability pp, the first trial succeeds (so N=1N = 1) or fails (so N=1+N′N = 1 + N' with N′N' an independent copy):

E[N2]=p⋅1+q E[(1+N)2]=1+2q E[N]+q E[N2].\mathbb{E}[N^2] = p \cdot 1 + q\,\mathbb{E}[(1 + N)^2] = 1 + 2q\,\mathbb{E}[N] + q\,\mathbb{E}[N^2] .

With E[N]=1/p\mathbb{E}[N] = 1/p this gives E[N2]=(2−p)/p2\mathbb{E}[N^2] = (2 - p)/p^2 and Var⁡(N)=(1−p)/p2\operatorname{Var}(N) = (1 - p)/p^2. For a die waiting for a 6, E[N2]=66\mathbb{E}[N^2] = 66 and Var⁡(N)=30\operatorname{Var}(N) = 30: 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 Es=1+∑P(s→s′)Es′E_s = 1 + \sum P(s \to s')E_{s'}, and set the target to 0.
  • Build big waits from small ones: Tk=2Tk−1+2T_k = 2T_{k-1} + 2 gives 2k+1−22^{k+1} - 2 for kk heads in a row.
  • Fair-coin pattern waits are the sum of 2j2^j over the self-overlap lengths jj; 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 −k2-k^2.
  • Expected passage times split into level-by-level differences; the reflecting walk takes n2n^2 steps to reach nn.
  • 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).