Markov chains
A Markov chain is a random process with amnesia: given the present state, the future is independent of the past. That one assumption buys an enormous amount of machinery — transition matrices, stationary distributions, and above all first-step analysis, the single most-used tool in applied probability. This chapter builds the theory, then drills the tool on the classics: expected flips to HH versus HT, frogs, mazes, deuce, and a drunk near a cliff.
Most real systems have long memories, but a surprising number are well described by a handful of stateswhose label absorbs everything relevant about the past: the weather is “wet” or “dry”, the market is “calm” or “turbulent”, your coin-flip progress toward HH is “nothing yet” or “one head”. Once the state summarises the past, the process restarts from the state — and every question about the future becomes linear algebra. That is the whole trick: choose the state so the process forgets, then condition on one step.
The Markov property and transition matrices#
A discrete-time process on a countable state space is a Markov chain if for all states and all ,
The chain is time-homogeneous when does not depend on . Collect the one-step probabilities into the transition matrix : every entry is non-negative and every row sums to one (a stochastic matrix). If the distribution of is the row vector , then — the entire dynamics is matrix multiplication.
A running example with a quant flavour: a two-state regime chain for daily market conditions, calm (C) or turbulent (T),
Calm days overwhelmingly stay calm; turbulence persists but decays. This is exactly the structure behind regime detection — a hidden Markov model is this chain with noisy observations bolted on.
Write . Condition on the state at an intermediate time using the law of total probability (see axioms & conditioning) and apply the Markov property to drop the past:
But the right side is precisely the entry of the matrix product . By induction the -step transition matrix is : powers of the one-step matrix. Every multi-step question about a Markov chain is a statement about matrix powers.
Worked example (by hand). Starting calm, what is the probability of turbulence two days out? Sum over the intermediate day:
Either you stay calm a day and then flip, or you flip immediately and turbulence persists. Note : risk accumulates with horizon, but not linearly — the two-step matrix is already blending toward the long-run mix computed below.
Classifying states#
The long-run behaviour of a chain is controlled by a small taxonomy. State is accessible from if for some ; states that access each other communicate, and a chain whose states all communicate is irreducible.
- Recurrent: starting from , the chain returns to with probability 1 (and hence infinitely often). If the expected return time is finite the state is positive recurrent.
- Transient: the return probability is ; the chain visits the state only finitely many times, then leaves forever. Equivalent test: .
- Periodic: the period of is . A chain that can only return at even times (period 2, like the simple random walk) never settles pointwise — it oscillates. Aperiodic means .
- Absorbing: — once entered, never left. Ruin at zero wealth is the canonical example.
In a finite chain, at least one state must be recurrent (the chain has nowhere else to go), and all states of an irreducible finite chain are positive recurrent. Transience only truly bites on infinite state spaces — the random walk in three dimensions is the famous example, taken up in random walks & Brownian motion.
Stationary distributions and convergence#
A distribution (a row vector, , ) is stationary if it is a fixed point of the dynamics:
Start the chain in and it stays in forever. The fundamental theorem for finite chains: if the chain is irreducible, a stationary distribution exists and is unique, and . If additionally the chain is aperiodic, then from any start,
and long-run time averages converge to -averages (the ergodic theorem — the Markov cousin of the law of large numbers).
Worked example (by hand). Solve for the regime chain. With , the balance equation for state C reads , i.e. . Probability out of calm must match probability into calm. With :
The market spends 80% of days calm in the long run, and the expected return time to turbulence is days. The general two-state shortcut is worth memorising: with switch probabilities (out of state 1) and (out of state 2), .
A distribution satisfies detailed balance if for every pair — probability flows between each pair of states in equal and opposite amounts. Summing over :
which is exactly . Detailed balance is stronger than stationarity (it makes the chain look statistically identical run backwards — reversible), but it is much easier to solve: pairwise equations instead of a global linear system. Every two-state chain is reversible — check ours: . This is also the design principle behind MCMC samplers: build to satisfy detailed balance with respect to the distribution you want to sample.

The speed of convergence is geometric, governed by the second-largest eigenvalue modulus of (here ): distance to stationarity shrinks by a factor per step. Slow mixing (eigenvalue near 1) means persistent regimes — the statistical reason regime filters lag turns.
import numpy as np
rng = np.random.default_rng(11)
P = np.array([[0.95, 0.05],
[0.20, 0.80]]) # states: 0 = calm, 1 = turbulent
# --- 1) long-run occupation matches pi = (0.8, 0.2) ---------------------
n, x = 200_000, 0
visits = np.zeros(2)
for _ in range(n):
visits[x] += 1
x = rng.choice(2, p=P[x])
print(visits / n) # ~ [0.800, 0.200]
# eigenvector check: left eigenvector of P for eigenvalue 1
w, V = np.linalg.eig(P.T)
pi = np.real(V[:, np.argmax(w)]); pi /= pi.sum()
print(pi) # [0.8, 0.2]
# --- 2) first-step analysis check: expected fair flips to see HH = 6 ----
def flips_to_HH():
prev, t = None, 0
while True:
c = rng.integers(2); t += 1 # 1 = heads
if prev == 1 and c == 1:
return t
prev = c
print(np.mean([flips_to_HH() for _ in range(200_000)])) # ~ 6.0First-step analysis: the essential tool#
Almost every Markov problem — hitting probabilities, expected durations, win probabilities from a score — yields to one move: condition on the first step. Let be a target set. Define the hitting probability and the expected hitting time . Conditioning on and using the Markov property to restart the chain gives linear systems:
Read the second system aloud and it is obvious: one step happens no matter what, plus wherever you land, you face the same problem from the new state. The boundary conditions do the rest. (When several solutions exist — possible on infinite spaces — the hitting probabilities are the minimal non-negative solution.)
Worked example 1 — hitting probability. A fair gambler starts with 1 unit and quits at 0 (broke) or 3 (target); each round is with probability . Let be the probability of reaching 3 from . Boundaries , ; interior:
Substituting: , so and — in general for a fair game, linear in wealth. The full gambler’s-ruin treatment, including the biased case and expected duration via optional stopping, is in martingales & optional stopping — first-step analysis and martingale arguments are two roads to the same linear systems.
Worked example 2 — expected hitting time. Expected rolls of a fair die to see two consecutive sixes. States: (no progress) and (last roll was a six). Let be expected remaining rolls:
The first equation gives ; substituting the second, , so . Six rolls to get one six, but 42 to get two in a row — failure late in the pattern throws you all the way back to the start, and that resetting is expensive. This asymmetry is the heart of Problem 1 below.

Absorbing chains and the fundamental matrix#
First-step analysis scales to any number of states by matrix algebra. Order states with the transient ones first and write the transition matrix in canonical block form:
where maps transient to transient and transient to absorbing. The fundamental matrix is : entry is the expected number of visits to transient state starting from (each power of counts visits at one time step). Then expected absorption times and absorption probabilities come out in one line each:
Worked example (by hand). The gambler’s chain on has transient states with
So — two expected rounds from either interior state (matching the general fair-game formula ) — and reproduces from the previous section. One matrix inverse answers every hitting question about the chain at once.
Practice problems#
A fair coin is flipped until the pattern HH first appears; separately, until HT first appears. Find both expected waiting times and explain why they differ.
Solution. HH. Track progress with states (no useful history) and (last flip H, no HH yet). First-step equations for the expected remaining flips :
From the first, . Substitute the second: , hence (and ).
HT. Same states, but now from a head is not a setback — it leaves you still holding a head:
The second equation solves alone: ; then .
Why they differ. Both patterns occur with the same probability in any two given flips, but the failure geometry differs. Waiting for HH, a tail after a head destroys all progress — back to . Waiting for HT, once you hold a head you can never lose it: extra heads keep you at , and the first tail finishes. Equivalently, HH can overlap with itself (occurrences can share a flip), which forces occurrences to clump and stretches the mean gap between them; the general statement is the pattern-overlap (Conway leading-number) correction, and the elegant martingale proof of it is the ABRACADABRA argument in martingales & optional stopping. A classic follow-up: “so which pattern appears firstmore often?” — for HH vs HT it is a tie by symmetry of the first two outcomes, which is a different question than the mean wait.
A frog sits on one of three lily pads arranged in a triangle. Each minute it jumps to one of the other two pads uniformly at random. What is the expected time until it first returns to its starting pad?
Solution. Slick route: the chain is irreducible on 3 states and symmetric, so the stationary distribution is uniform, . By the return-time theorem, . Systematic route (first-step): from either non-start pad, let be the expected time to reach the start; by symmetry both non-start pads share it: , so , and the return time is . The shortcut is worth volunteering: it dispatches every “expected return time on a symmetric graph” variant (a knight on a chessboard corner is the famous one — return time , since the random walk on a graph has by detailed balance).
A rat is in a chamber with three doors, chosen uniformly at random each attempt. Door 1 leads outside after a 2-minute tunnel. Door 2 returns it to the chamber after 3 minutes; door 3 returns it after 5 minutes. Expected time to get out?
Solution. Let be the escape time and condition on the first choice; by the Markov property the rat restarts fresh after a returning tunnel (it learns nothing):
so and minutes. Sanity check via a renewal view: each attempt costs on average minutes and succeeds with probability , so the expected number of attempts is 3 and . The trap variant gives the rat memory (it never repeats a door); then the conditioning changes and the answer drops — always ask whether the process resets.
From deuce, a server wins each point independently with probability . A player must lead by two points to take the game. What is the probability the server wins from deuce, and the value for ?
Solution. States: deuce , advantage-server , advantage-receiver . With and the win probability from deuce:
The slick reading: play points in pairs. A pair is decisive only if it splits or ; conditional on a decisive pair, the server wins with probability , and indecisive pairs (probability ) return to deuce — memorylessness makes them irrelevant. For : — a 60% point edge compounds to a 69% game edge from deuce. Expected number of points from deuce is (geometric number of pairs times two).
A drunk stands one step from a cliff edge. Each second he steps toward the edge with probability and away with probability . What is the probability he eventually falls off?
Solution. Let be the probability of ever reaching the edge from steps away. Homogeneity plus the strong Markov property give the multiplicative structure : to fall from distance 2 you must first reach distance 1, then fall from there, and the two stages are independent replicas. First-step analysis at :
Hitting probabilities are the minimal non-negative solution, so . In general, stepping toward doom with probability gives ; at the answer jumps to 1 — the fair walk is recurrent (see random walks), so even a fair game against a barrier is eventually fatal. That discontinuity at is the point worth dwelling on.
If it rains today it rains tomorrow with probability 0.7; if it is sunny it rains tomorrow with probability 0.4. (a) Given rain today, the probability of rain the day after tomorrow? (b) The long-run fraction of rainy days?
Solution. (a) Chapman–Kolmogorov, summing over tomorrow: . (b) Balance flow between states: , so . Note the two-step answer 0.61 is already drifting from 0.7 toward the stationary 0.571 at geometric rate per day: after days, — a closed form worth quoting to close the question.
Next:the drunk near a cliff was a preview; the next chapter gives gambler’s ruin its own full treatment — solved three ways, by difference equations, martingales, and symmetry — and follows the consequences all the way to risk of ruin. Gambler’s ruin & fair games.

