Lecture 5: Markov Chains, Random Walks & MC Sampling
Memoryless random motion settling into a unique stationary distribution, made into a sampler (MCMC, Metropolis–Hastings); mixing via coupling, stopping times and expanders; sampling becomes counting.
Last updated 27 June 2026
Lecture 5 — Markov Chains & Random Walks → Monte Carlo Sampling
Course 2-INF-135/15 Pravdepodobnostné algoritmy, LS 2025/26.
Source slides: 05_MC.pdf (46 pages).
Štátnicové syllabus topics covered here: Markov chains, transition matrix and
stationary distribution; connection to eigenvalues; mixing (variation distance),
strong uniform stopping times; sampling via random walks (random graphs with
prescribed degrees, random knapsack solutions); reversible chains and the
Metropolis–Hastings algorithm (how to build a chain with a given stationary
distribution).
The one-paragraph map of the whole lecture
A Markov chain is random motion with no memory: where you go next depends only
on where you are now, not on how you got there. The deep fact is that a “nice” chain
forgets its starting point — run it long enough and the probability of being in
state i converges to a single number πi that does not depend on where you
began. That number is the stationary distribution.
This turns into a powerful algorithmic machine. Suppose you want to sample an object
from some weird, exponentially large space S according to a prescribed distribution
σ (a uniform independent set, a random knapsack solution, a random shuffle of a
deck). You cannot list S. But if you can design a chain that walks around S and
whose stationary distribution is exactly σ, then you just run the walk and read
off where you land. Two questions then dominate the entire lecture:
How do I BUILD a chain with a prescribed stationary distribution σ?
→ the idea of reversibility / detailed balance, culminating in the
Metropolis–Hastings algorithm.
How LONG must I run it? → mixing time, measured in variation distance,
and bounded three ways: coupling, strong uniform stopping times, and
eigenvalues (expanders mix fast).
The closing payoff: sampling lets you count (estimate the size of huge sets —
FPRAS, #DNF), and as a bonus, expander walks recycle random bits to amplify BPP
using O(k) bits instead of O(kn).
1. What a Markov chain is
A stochastic process is just a family of random variables indexed by time,
X={Xt∣t∈T}, where Xt is “the state at time t.” We assume
discrete time (t=0,1,2,…) and a discrete state space{0,1,2,…} (finite or countable).
The process is a Markov chain if it has the memorylessness (Markov) property:
Intuition. The present screens off the past from the future. The only thing the
chain “knows” is its current state; the entire history before that is irrelevant to
what happens next. Equivalently, for times u<t<v, the past (Xu) and the
future (Xv) are conditionally independent given the present (Xt):
Pr[Xu=i,Xv=k∣Xt=j]=Pr[Xu=i∣Xt=j]⋅Pr[Xv=k∣Xt=j].
The transition matrix
All the dynamics live in a single matrix. Let
pi,j=Pr[Xt=j∣Xt−1=i]
be the probability of stepping from i to j in one move (assumed time-homogeneous
— the same at every t). Collect them into the transition matrixP=(pi,j).
Each row sums to 1 (from i you must go somewhere):
j≥0∑pi,j=1for every i.
A matrix with non-negative entries and rows summing to 1 is called stochastic — and
every such matrix is the transition matrix of some chain.
How distributions evolve — it’s just matrix multiplication
Let pi(t)=Pr[system is in state i at time t] and collect these
into a row vectorpˉ(t)=(p0(t),p1(t),…), the distribution over states
at time t. To be in state i at time t, you were in some state j at time t−1
and stepped j→i:
pi(t)=j≥0∑pj(t−1)pj,i⟺pˉ(t)=pˉ(t−1)P
Iterating, the m-step transition matrix is just the matrix power P(m)=Pm,
and
pˉ(t+m)=pˉ(t)Pm.
Punchline. A Markov chain is a stochastic matrix. Running the chain = repeatedly
multiplying a distribution vector by P. Everything that follows — convergence,
stationary distributions, mixing rates — is secretly a statement about the powers
Pm and the eigenvalues of P. Hold that thought; it returns in §11 (expanders).
2. First examples — random walks that solve problems (2SAT, 3SAT)
Before the theory, two examples show why we care: a random walk on assignments solves
satisfiability, and the chain analysis gives the running time.
2SAT — the symmetric walk, O(n2)
Algorithm (Papadimitriou). Start from any truth assignment α0. While the
formula is unsatisfied, pick an unsatisfied clause and flip a uniformly random one of
its two literals. Repeat.
Why does this make progress? Fix a satisfying assignment α∗ (assume one exists).
An unsatisfied 2-clause has both its literals wrong under the current assignment, but
α∗ satisfies the clause, so α∗ disagrees with us on at least one of
those two variables. Flipping a random one of the two therefore moves us closer to
α∗ with probability ≥21.
Track j = the number of variables on which we currently agree with α∗
(Hamming distance is n−j). This is (a lower bound on) a chain on {0,1,…,n}:
at j=n we have found a satisfying assignment: hn=0;
at j=0 any flip increases agreement: h0=1+h1;
in between, with prob 21 we go to j+1, with prob 21 to j−1:
hj=1+21hj−1+21hj+1.
Here h_j = $ expected number of steps to reach $\alpha^* starting from agreement j.
Solving the recurrence (it telescopes to hj=hj+1+(2j+1)) gives
h0=n2
so the symmetric walk finds a satisfying assignment in expected O(n2) steps. (This
is the classic gambler’s-ruin / drift argument: a fair walk on a line of length n takes
Θ(n2) time to cross it.)
3SAT — the biased walk, and why restarts win
For 3SAT an unsatisfied 3-clause has three literals; α∗ disagrees on at least
one, so a random flip moves us toward α∗ with probability only 31 and
away with probability 32. The recurrence becomes biased:
hj=1+32hj−1+31hj+1,hj=hj+1+(2j+2−3).
A walk biased away from the target takes exponential time: h0=O(2n). Running
one long walk is hopeless.
The fix (Schöning). Don’t run one long walk — run many short walks from fresh
random starts. The key insight on the slide: “if a satisfying α exists, then
there are many” assignments from which a short walk reaches it. A random start lands
within a favourable distance often enough that capping each walk at O(n) steps and
restarting gives
h0=O(n3/2(4/3)n),
dramatically better than 2n. (This is the random-walk k-SAT algorithm previewed in
the derandomization lecture — derandomized there by sweeping a covering code instead of
guessing the start.)
Professor-pleaser. The same random-flip rule is polynomial for 2SAT and
exponential for 3SAT, and the only thing that changed is the drift of the
induced walk on Hamming distance: fair coin (21/21) → O(n2); biased
coin (31/32) → 2n. The behaviour of the algorithm is entirely the
behaviour of the underlying Markov chain. This is the whole reason to study chains.
3. Classifying states — which chains “settle down”?
For a chain to forget its start and converge, it must be structurally well-behaved. The
vocabulary (this is the part to be able to recite in the oral):
Reachable (j reachable from i): pi,j(t)>0 for some t.
Communicating states: each reachable from the other.
Irreducible chain: every state communicates with every other — i.e. the directed
graph of the chain is a single strongly connected component. (You can get from
anywhere to anywhere.)
Recurrent / persistent state i: you return to it with certainty.
Let ri,j(t)=Pr[first visit to j from i is at time t].
Then i is recurrent iff
fi,i=t≥1∑ri,i(t)=1.
Transient (prechodový) state: fi,i=∑tri,i(t)<1 — there is
positive probability you never come back.
Absorbing state: once entered, never left (pi,i=1).
A recurrent chain has all states recurrent.
Among recurrent states there is a subtle but exam-relevant split. The mean return time
is
hi,i=t≥1∑t⋅ri,i(t).
Positive recurrent: hi,i<∞ (you come back, and in finite expected time).
Null recurrent: hi,i=∞ (you come back with probability 1, but the
expected wait is infinite!).
The null-recurrent example (worth knowing — it’s a classic trap). Consider a chain
on {1,2,3,…} where from i you go up to i+1 with probability
i+1i and home to 1 with probability i+11. The probability of
first returning to 1 at exactly time t is
r1,1(t)=climb 1→t21⋅32⋯tt−1⋅t→1t+11=t1⋅t+11=t(t+1)1.
Then f1,1=∑tt(t+1)1=1 (telescopes), so state 1 is recurrent —
but
h1,1=t∑t⋅t(t+1)1=t∑t+11=∞.Null recurrent. You always come home, but the average homecoming time is infinite.
This cannot happen in a finite chain (next lemma).
Two equivalent tests for recurrence
A clean characterisation via the m-step return probabilities:
i is recurrent⟺t=1∑∞pi,i(t)=∞,i is transient⟺t=1∑∞pi,i(t)<∞.Why: if i is transient with return probability q<1, the number of returns is
geometric, and ∑tpi,i(t)=∑nqn=1−qq<∞. If recurrent,
each return is certain so the expected number of returns — which equals this sum — is
infinite.
Periodicity and ergodicity
Period of state i: gcd{t:pi,i(t)>0} — the gcd of all times at which
return is possible. Aperiodic = period 1.
Quick check the slide asks: a random walk on an undirected cycle has period 2
if the length is even (you can only come back after an even number of steps) and
period 1 if the length is odd (odd cycles let you “turn around”). Bipartiteness =
period 2. This is exactly why we add self-loops to kill periodicity later.
Ergodic state: aperiodic and positive recurrent — “you come back, in finite
expected time, but at irregular times.” An ergodic chain has all states ergodic.
Lemma (finite chains are well-behaved). In a finite Markov chain:
there is at least one recurrent state;
all recurrent states are positive recurrent (no null recurrence in finite chains).
Stationary distribution
A distribution πˉ is stationary if it is a fixed point of the dynamics:
πˉ=πˉP
i.e. if you start in πˉ, after one step you are still in πˉ (and hence
forever). It is a left eigenvector of P with eigenvalue 1.
4. The Fundamental Theorem of Markov Chains
This is the theorem of the lecture — the precise statement that “nice chains forget
their start.”
Theorem (Fundamental / hlavná veta). In an irreducible, finite, aperiodic
Markov chain:
every state is ergodic;
there exists a unique stationary distribution π;
fi,i=1 and the mean return time is hi,i=πi1;
the long-run fraction of time spent in i converges to πi:
t→∞limtN(i,t)=πi, where N(i,t) counts
visits to i in t steps.
Equivalently (the “convergence” form):
3′. t→∞limPj,itexists and is independent of the
starting state j;
4′. πi=t→∞limPj,it=hi,i1.
Read parts 3′–4′ slowly — they are the magic:
Intuition.Pj,it is the probability of being at i after t steps given
you started at j. The theorem says this stops depending on j. The chain
erases the memory of its origin. Where you end up is governed only by the chain’s
structure, summarised in π. And πi=1/hi,i has a lovely reading: a state
you return to quickly (small mean return time) is a state you spend a lot of time in
(large stationary probability). Frequently visited ⇔ short return time.
The three hypotheses each pull their weight:
irreducible → the limit can’t depend on j (otherwise disconnected pieces keep
separate fates);
aperiodic → the limit exists (a period-2 chain oscillates forever and never
settles — recall the even cycle);
finite → positive recurrence is automatic (no null-recurrent escape to infinity).
5. Computing π — cuts and reversibility (the load-bearing trick)
How do you actually findπ? Solve πP=π with ∑iπi=1. Written
out component-wise, the equation πi=∑jπjPj,i is a balance / cut
condition:
j∑πjPj,i=πi=πij∑Pi,j.
The left side is flow into i; the right side is flow out of i. Stationarity =
global balance: total probability flowing into each state equals total flowing out.
Solving the full linear system is doable but painful. There is a much stronger, much
easier-to-check sufficient condition.
Theorem (detailed balance ⇒ stationary). Let the chain be finite, irreducible,
ergodic with matrix P, and let π=(π1,…,πn) be non-negative with
∑iπi=1, and
πiPi,j=πjPj,ifor every pair i,j (the detailed balance
/ reversibility condition).
Then π is the (unique) stationary distribution, and the chain is time-reversible.
Proof — one line. Sum detailed balance over i:
i∑πiPi,j=i∑πjPj,i=πji∑Pj,i=πj,
which is exactly the stationarity equation (πP)j=πj. ∎
Why this is the whole game. Global balance (the true stationarity equation) couples
all states together — a big linear system. Detailed balance is a local,
pairwise condition: just check each edge i↔j in isolation. It is
strictly stronger (not every chain is reversible), but when it holds it is trivial to
verify, and — crucially — it is the lever we use to engineer a chain with a
prescribedπ. “Reversible” means the chain looks statistically the same run
forwards or backwards in time. Remember this condition; the entire Metropolis
construction in §8–§9 is just “rig the transition probabilities so detailed balance
holds for the π I want.”
6. Random walks on undirected graphs
The most important concrete chain. Given a connected undirected graph G=(V,E), the
simple random walk steps from v to a uniformly random neighbour:
Pi,j=deg(i)1if (i,j)∈E,else 0.
(Aperiodic ⟺G is not bipartite — same parity-of-cycles fact as before.)
Theorem. The simple random walk on a connected non-bipartite graph converges to the
stationary distribution
πv=2∣E∣deg(v)
— proportional to degree. High-degree vertices are visited more.
Check. It sums to 1: ∑v2∣E∣deg(v)=2∣E∣2∣E∣=1 (handshake
lemma). And it satisfies detailed balance — the cleanest possible verification:
πuPu,v=2∣E∣deg(u)⋅deg(u)1=2∣E∣1=2∣E∣deg(v)⋅deg(v)1=πvPv,u.
Both directions of an edge carry the same flow 2∣E∣1. (This is exactly why
§5’s reversibility machinery is so handy.)
By the Fundamental Theorem, the mean return time to u is
hu,u=πu1=deg(u)2∣E∣.
Hitting times and cover time — why a walk explores fast
Hitting time on an edge. If (u,v)∈E, then the expected time to go from v to u
is bounded:
hv,u<2∣E∣.Proof. Condition the return-to-u time on the first step out of u:
deg(u)2∣E∣=hu,u=deg(u)1w∈N(u)∑(1+hw,u).
Multiply by deg(u): 2∣E∣=∑w∈N(u)(1+hw,u). Every term is positive, so
each single 1+hw,u<2∣E∣; in particular hv,u<2∣E∣. ∎
Cover time = expected time to visit all vertices, from the worst start.
Theorem.cover time<4∣V∣∣E∣.
Proof idea (elegant). Fix a spanning tree. Walk the tree in a fixed closed tour
(e.g. a DFS traversal, around the tree) that crosses each of its ∣V∣−1 edges once in
each direction — 2(∣V∣−1) edge-traversals. The expected time for each traversal of an
edge (vi,vi+1) is hvi,vi+1<2∣E∣. Summing,
cover time≤i∑hvi,vi+1<2(∣V∣−1)⋅2∣E∣<4∣V∣∣E∣.■
Why this matters algorithmically. A random walk explores a connected graph in
polynomial time using essentially no memory — you only remember your current vertex.
The headline application: undirected s–t connectivity (USTCON) in randomized
log-space. To decide whether t is reachable from s, just walk from s for
O(∣V∣∣E∣)=poly steps; if you hit t, accept. The walk needs only
O(logn) bits (the current vertex + a counter). This is the basis of the result
USTCON∈RL — and famously was later derandomized to
L by Reingold. The cover-time bound is exactly the running-time guarantee.
7. From walks to sampling — the Monte Carlo Markov Chain (MCMC) idea
Here is the conceptual pivot of the lecture.
Problem. Sample an object from a huge space S according to a prescribed
distribution σ. (S is exponential — you cannot enumerate it.)
Solution (MCMC). Design an ergodic Markov chain such that
its state space is S (the objects you want to sample), and
its stationary distribution is the desired σ.
Then run the chain. By the Fundamental Theorem it converges to σ from any
starting state, so after enough steps the current state is an (almost) σ-sample.
To get several near-independent samples, run a long walk x0,x1,x2,… and take
states spaced r apart:
x0rxrrx2rrx3r⋯
If r is at least the mixing time, xr,x2r,x3r,… are nearly independent
σ-samples.
Two quantities control the cost, and they organize the rest of the lecture:
r = the mixing time — how long until one step “looks like” σ. (The hard
part; §10–§11.)
the cost of one step — want a small neighbourhoodN(x) so each move is cheap.
The design freedom and the two sub-problems. We get to invent the chain. That
raises exactly the two questions from the map: (1) how do we force the stationary
distribution to be the σ we want (uniform? weighted?) — §8–§9; and (2) how do we
bound r so we know when to stop — §10–§11.
We assume a symmetric neighbourhood structure{N(x)} on S: $y \in N(x) \iff x
\in N(y)$ (an undirected “move graph” on the objects), and we want N(x) small.
8. Building a chain with uniform stationary distribution
First the easy target: \sigma = $ **uniform** on $S. Naïvely walking the move-graph
gives πv∝deg(v) (§6) — not uniform, because different objects have
different numbers of neighbours. The fix is to equalize the transition probabilities by
padding with self-loops.
Lemma (uniform sampler). Let Ω be a finite state space with neighbourhood
structure {N(x)}, N=maxx∣N(x)∣. Pick any M>N and define the chain
P(x,y)=⎩⎨⎧1/M01−∣N(x)∣/Mx=y,y∈N(x),x=y,y∈/N(x),x=y(self-loop).
If this chain is irreducible and aperiodic, its stationary distribution is uniform,
πx=1/∣Ω∣.
Proof. Every off-diagonal transition probability is the same constant1/M,
regardless of x or y (the self-loop soaks up the difference in degrees). So
P(x,y)=P(y,x)=1/M — the matrix is symmetric. Detailed balance with the uniform
πx=πy=1/∣Ω∣ reads πxP(x,y)=πyP(y,x), which holds because both
π’s and both P’s are equal. By §5, uniform is stationary. ∎
The idea in one phrase.Self-loops are a thermostat for degree. Every vertex
“spends” ∣N(x)∣/M of its probability stepping out and parks the remaining
1−∣N(x)∣/M on itself, so outgoing edges all carry the same weight 1/M.
Equal edge weights ⇒ symmetric matrix ⇒ uniform stationary. We choose M>N strictly
so every state has a positive self-loop, which also kills periodicity for free.
Example — sampling a uniform Independent Set
State space \Omega = $ all independent sets of $G. Neighbourhood: $N(x) = $ independent
sets differing from x in one vertex. The chain:
Uniform-IS walk.
X0← any independent set.
To compute Xi+1: pick a uniform random vertex v∈V.
if v∈Xi: set Xi+1←Xi∖{v} (remove);
if v∈/Xi and Xi∪{v} is independent: $X_{i+1} \leftarrow X_i \cup
{v}$ (add);
otherwise Xi+1←Xi (stay — this is the self-loop).
Picking v among all ∣V∣ vertices, and staying when the move is illegal, is exactly the
“M>N with self-loops” construction (here M=∣V∣). As long as G has at least one
edge there is always some illegal move from some state, guaranteeing a self-loop, hence
aperiodicity. Stationary distribution: uniform over all independent sets.
9. Building a chain with a prescribed non-uniformπ — Metropolis
Now the general target: we want each object x sampled with a prescribed probability
πx. Often π is given only up to normalization:
πx=Bb(x),b(x)>0,B=x∈Ω∑b(x),
and the normalizer B (a sum over the entire exponential space!) is unknown and
hopeless to compute. The triumph of Metropolis is that we never need B.
Lemma (Metropolis). Given {N(x)}, N=maxx∣N(x)∣, M>N, and any desired
πx>0, define
P(x,y)=⎩⎨⎧M1⋅min{1,πxπy}01−y=x∑P(x,y)x=y,y∈N(x),x=y,y∈/N(x),x=y.
If irreducible and aperiodic, its stationary distribution is exactly π.
Proof — detailed balance again. Take x=y neighbours with (WLOG) πx≤πy.
Then min{1,πy/πx}=1, so P(x,y)=1/M; and $\min{1,\pi_x/\pi_y} =
\pi_x/\pi_y, so $P(y,x) = \frac1M\cdot\frac{\pi_x}{\pi_y}. Check:
πxP(x,y)=Mπx,πyP(y,x)=πy⋅M1⋅πyπx=Mπx.
Equal — detailed balance holds, so π is stationary. ∎
The two beautiful features.
Only ratios πy/πx appear. The unknown normalizer B cancels:
πy/πx=b(y)/b(x). We can sample from π without ever knowing the total
weight B — exactly the situation in every real counting/physics application.
The acceptance rule is a thermostat toward π. Propose a uniform neighbour
move (1/M). Always accept a move to a more-probable state (πy≥πx);
accept a move to a less-probable state only with probability πy/πx.
Detailed balance is satisfied by construction, so the walk pools where π is large.
Metropolis for weighted Independent Sets
We want Pr[independent set I]∝λ∣I∣ for a parameter λ>0:
πx=Bλ∣Ix∣,so⎩⎨⎧λ=1:λ<1:λ>1:uniform,smaller sets favoured,larger sets favoured (toward max IS).
The ratio for adding a vertex is πy/πx=λ∣I∣+1/λ∣I∣=λ;
for removing, 1/λ. So the algorithm needs only λ:
Metropolis-IS.
X0← some independent set.
To compute Xi+1: pick v∈V uniformly (prob 1/M, M=∣V∣).
if v∈Xi: remove it with probability min{1,1/λ};
if v∈/Xi and Xi∪{v} independent: add it with probability
min{1,λ};
otherwise stay.
The detailed-balance check (πxP(x,y)=πyP(y,x)) goes through with the λ
ratios, and — the punchline on the slide — “B sme nepotrebovali :-)”: we never
needed the normalizer.
Metropolis–Hastings — the general recipe (asymmetric proposals)
What if the proposal mechanism itself is not symmetric? Let Q be any irreducible
proposal chain (q_{ij} = $ probability of proposing $j from i), and π the desired
distribution.
Metropolis–Hastings. From i, propose j according to Q. Accept the move with
probability
α=min{πiqijπjqji,1}
(when Q is symmetric, qij=qji, this collapses to the plain Metropolis
α=min{πj/πi,1}). Otherwise stay at i.
The resulting transition pij=qijα satisfies detailed balance with π:
the correction factor qji/qij exactly cancels the asymmetry of the proposal, so
πipij=πjpji.
Professor-pleaser — the unifying statement of §8–§9.Metropolis–Hastings is a
universal machine for manufacturing a Markov chain with any prescribed stationary
distribution, using only the ratios of the target probabilities. It works by
forcing detailed balance (§5): start from any convenient proposal walk, then bend
the acceptance probabilities until πipij=πjpji holds on every edge.
Reversibility is not a curiosity — it is the design principle of all of MCMC.
10. How long? — variation distance, mixing time, and coupling
We can build the chain; now we must know when its distribution is close enough to
π. We need (a) a notion of “close,” and (b) tools to bound the time to get there.
Variation distance — the right notion of “close”
For two distributions D1,D2 on a countable S, the total variation distance is
∥D1−D2∥:=21x∈S∑∣D1(x)−D2(x)∣.
Lemma (the event form). $;\displaystyle |D_1 - D_2| = \max_{A\subseteq S}
|D_1(A) - D_2(A)|;$ where Di(A)=∑x∈ADi(x).
Intuition. Variation distance is the largest disagreement on any event: no
matter what yes/no question A you ask, the two distributions assign A probabilities
differing by at most ∥D1−D2∥. The maximizing A is “all x where D1>D2.”
The factor 21 makes the range [0,1]. This is the operational meaning: if
variation distance is ≤ε, no statistical test can tell the two apart
with advantage more than ε.
Mixing time
Let π∗ be stationary, and pxt the distribution after t steps starting from x.
Define
Δx(t)=∥pxt−π∗∥,Δ(t)=x∈SmaxΔx(t),τx(ε)=min{t:Δx(t)≤ε},τ(ε)=xmaxτx(ε)(mixing time).
A chain is rapidly mixing if τ(ε) is polylog in 1/ε
(and polynomial in the input size) — fast enough to be useful as a sampler. The whole
ε-uniform sampling goal is: run until ∥D−U∥≤ε.
Coupling — the workhorse for bounding mixing time
How do you prove a chain mixes fast? Coupling is the dominant technique.
Definition. A coupling of a chain M (on S) is a chain Zt=(Xt,Yt) on
S×S such that each coordinate, viewed alone, is a faithful copy of M:
Pr[Xt+1=x′∣Zt=(x,y)]=Pr[Mt+1=x′∣Mt=x],Pr[Yt+1=y′∣Zt=(x,y)]=Pr[Mt+1=y′∣Mt=y].
The two copies may be correlated however we like (that’s the design freedom), as long
as the marginals are correct.
Lemma (Coupling Lemma). If a coupling Zt=(Xt,Yt) satisfies, for some time T,
Pr[XT=YT∣X0=x,Y0=y]≤εfor all x,y,
then the mixing time obeys τ(ε)≤T.
Why coupling works — the picture. Run two copies of the chain at once: one started
at the worst state x, the other started in the stationary distributionπ (so
the second copy is always exactly π). Couple their randomness so that once they
meet, they move together forever. At any time t, the variation distance of copy 1
from π is at most the probability the two copies have not yet met. So:
“design a coupling that makes the two copies collide quickly, and you have bounded the
mixing time.” When the copies are close, the chain is close to stationary.
11. Card shuffling — three couplings, three mixing analyses
Shuffling a deck of n cards is a random walk on the symmetric group Sn whose
stationary distribution is uniform (every permutation equally likely). “How many
shuffles to mix” = mixing time. Three classic shuffles, three techniques.
(a) Random transposition-to-top — coupling ⇒ coupon collector
A first attempt (move a random position to the top in both decks) does not couple
well. The clever coupling:
Pick a uniform card valueC∈{1,…,n} (not a position). In deck X, move
the card with value C to the top; in deck Y, also move the card with value C to
the top.
Now the key observation: once a card has been “named” C, it sits in the same relative
position in both decks forever after. So the two decks become identical as soon as
every value has been chosen at least once — which is exactly the coupon collector
problem. After nlnn+cn steps, the probability a specific card was never chosen is
Pr[specific card not yet on top]≤(1−n1)nlnn+cn≤e−(lnn+c)=ne−c,
so by a union bound over n cards,
Pr[some card never chosen]≤e−c.
By the Coupling Lemma, the mixing time is nlnn+O(n) — Θ(nlogn) shuffles.
(b) Top-in-at-random — strong uniform stopping time
Take the top card and insert it into a uniformly random position in the deck. A second,
equally powerful technique for proving “exactly uniform now”:
Definition (strong uniform stopping time / silno uniformné pravidlo zastavenia). A
(randomized) stopping rule T such that for every K, conditioned on T=K, the
permutation is exactly uniform. Stopping at T yields a perfectly uniform sample.
The stopping rule for top-in-at-random. Track the card that was originally on the
bottom. Stop the first time it gets inserted (reaches the top and goes in). Why is
this strong uniform? Each card inserted below the original bottom card lands in a
uniformly random position among those below it; by the time the original bottom card
itself is finally inserted, the entire deck below it has been built up uniformly at
random — so the full permutation is uniform, regardless of how long that took.
The time T until the original bottom card rises and inserts is, by the same structure, a
coupon-collector quantity again (the times Ti−Ti−1 to accumulate i cards
below match the inter-arrival times Vn−i+1−Vn−i of the collector).
Lemma (stopping-time bound on variation distance). If a shuffle has a strong uniform
stopping time T, then
∥Q∗k−U∥≤Pr[T>k].
Proof (the clean computation). For any event S⊆Sn, split on whether the
process has stopped by time k:
Q∗k(S)=j≤k∑=U(S),stopped⇒uniformPr[Xk∈S∣T=j]Pr[T=j]+Pr[Xk∈S∣T>k]Pr[T>k]=U(S)(1−Pr[T>k])+Pr[Xk∈S∣T>k]Pr[T>k]=U(S)+Pr[T>k]∈[−1,1](Pr[Xk∈S∣T>k]−U(S)).
Hence ∣Q∗k(S)−U(S)∣≤Pr[T>k] for every S; take the max over S. ∎
With k=⌈nlnn+cn⌉, the coupon-collector tail gives
Pr[T>k]≤e−c, so again Θ(nlogn) shuffles suffice.
The realistic shuffle: split the deck into two parts and interleave. The cleanest analysis
runs the inverse shuffle (assign each card a random bit, pull the 0-cards to the top
keeping relative order — equivalent to the forward riffle).
After k inverse shuffles each card carries a k-bit label (its sequence of bits). The
strong uniform stopping rule: stop when all n labels are distinct — at that moment
the cards are sorted by a uniformly random ordering, hence uniform. With K=2k possible
labels, “all n distinct” is exactly the birthday problem:
Theorem. After k riffle shuffles of n cards,
∥Rif∗k−U∥≤Pr[T>k]=1−i=1∏n−1(1−2ki).
By the birthday paradox the labels become distinct once 2k≫n2, i.e.
k≈2log2n; a sharper analysis gives the famous 23log2n≈7
shuffles for n=52 threshold.
Professor-pleaser — three shuffles, three classics. The same mixing question is
answered three different ways, each reducing the analysis to an elementary probability
gem: coupon collector (random-to-top, via coupling), coupon collector again
(top-in-at-random, via strong uniform stopping time), and the birthday paradox
(riffle). The two proof techniques — coupling and strong uniform stopping times —
are the two universal hammers for upper-bounding mixing time, and both reduce
“distribution is close to uniform” to “a simple combinatorial event has occurred.”
12. Eigenvalues, expanders, and rapid mixing
Recall pˉ(t)=pˉ(0)Pt — mixing is governed by the powers of P, hence by
its eigenvalues. This is the spectral route to bounding mixing time, and the natural
home of expanders.
Spectral facts for graphs
For an undirected (multi)graph let A(G) be the adjacency matrix (symmetric, so real
eigenvalues λ1≥λ2≥⋯≥λn with an orthonormal
eigenbasis). Key facts (state these; they recur):
Gconnected⇒λ2<λ1 (the top eigenvalue is simple);
∣λi∣≤d for all i, where d is the max degree;
d is an eigenvalue ⟺G is d-regular; then λ1=d with eigenvector
e1=n1(1,…,1) (the all-ones / uniform direction);
Gbipartite⟺ the spectrum is symmetric (λ↔−λ);
for connected G, bipartite ⟺−λ1 is an eigenvalue. A d-regular bipartite
graph has λn=−d.
The reading.λ1=d is the uniform/stationary direction. The spectral gapd−λ2 measures how fast everything else decays under repeated multiplication
by P=A/d: a big gap (λ2 far below d) means all non-uniform components die
quickly ⇒fast mixing. The negative end (λn near −d) signals
near-bipartiteness ⇒ near-periodicity, which we fix with self-loops.
Expanders
An (n,d,c)-expander is a bipartite d-regular (multi)graph G(X,Y,E) with
∣X∣=∣Y∣=n/2 that expands every subset:
∀S⊆X:∣Γ(S)∣≥(1+c(1−n2∣S∣))∣S∣.
Every set has many neighbours — the graph has no bottlenecks.
Theorem (expansion ⇔ spectral gap — Cheeger-type).
If G is an (n,d,c)-expander, then ∣λ2∣≤d−1024+2c2c2.
Conversely, if ∣λ2∣≤d−ε, then G is an (n,d,c)-expander
with c≥d22dε−ε2.
The two notions — combinatorial expansion (no small cuts) and a spectral gap (large
d−λ2) — are quantitatively equivalent. This is the deep structural fact behind
all of expander theory.
Random walk on an expander mixes rapidly
Take the walk P=A(G)/d. Kill periodicity by adding self-loops: Q=(I+P)/2, whose
eigenvalues shift to λi′=21+λi/d∈[0,1]. If $\lambda_2 = d
\varepsilon, then $\lambda_2' = 1 - \frac{\varepsilon}{2d} < 1.
Theorem (rapid mixing). For the lazy walk Q on an (n,d,c)-expander with
λ2≤d−ε, from any start q0, the relative deviation from
stationary obeys
Δ(t)≤n1.5(λ2′)t≤n1.5(1−2dε)t.
Since λ2′<1 is a constant bounded away from 1, Δ(t) drops below any
ε after only O(logn) steps — expanders mix in logarithmically many
steps. This is what “rapidly mixing” means in its purest form.
★ The application: amplifying BPP with O(k) random bits
A gorgeous payoff, and a classic exam topic linking this lecture to the complexity
lecture.
Setup. A BPP algorithm A uses n random bits and errs with probability ≤1/3.
We want to push the error down to 1/2k. The textbook way: run A on kindependent
random strings r1,…,rk and take the majority; Chernoff gives
Pr[majority of A(x,r1),…,A(x,rk) wrong]≤2−Ω(k).
But that costs k⋅n random bits. Random bits are expensive.Can we get error
1/2k using far fewer?
Yes — walk on an expander. Build an expander whose vertices are the n-bit
strings (so N=2n), d-regular with λ2′≤101 (e.g. degree
d=7, a (N,7,2α)-expander, Q=(I+A/7)/2). Take a single random walkX0,X1,…,X7k on it, and use the visited vertices as the random strings:
ri=Xi,compute maj(A(x,r0),A(x,r1),…,A(x,r7k)).
The cost: the first vertex needs n bits, but each step of the walk only needs
O(logd)=O(1) bits to choose a neighbour. Total:
n+O(k) random bits(vs. kn for independent sampling).
Theorem. $\Pr[\text{majority of } A(x,r_0),\dots,A(x,r_{7k}) \text{ wrong}] \le
1/2^k.$
Why it works (the deep point). The walk’s steps are highly correlated — yet
because the expander mixes rapidly, the sequence of visited vertices behaves almost
like independent samples for the purpose of a majority vote. The spectral gap
guarantees the walk doesn’t get “stuck” in a bad region: the fraction of steps landing
on bad strings concentrates just as it would for independent draws (an expander
Chernoff bound). Randomness is a costly resource, and expander walks let us recycle
it — getting the error reduction of k independent trials while paying for only
O(k) extra bits. This is a cornerstone of the “hardness vs. randomness” /
derandomization story.
13. From sampling to counting — Monte Carlo estimation and FPRAS
The final movement: once you can sample, you can count / estimate. This is the
Monte Carlo method proper.
Warm-up: estimating π (the constant)
Throw m uniform random points into the unit square; let Zi=1 if the i-th lands
inside the quarter disc (x2+y2≤1). With W=∑iZi, the fraction inside
estimates the area π/4:
E[W]=4mπ,estimator P=m4W.
Chernoff (Pr[∣X−μ∣≥δμ]≤2e−μδ2/3) on W gives
Pr[∣P−π∣≥επ]=Pr[∣W−E[W]∣≥εE[W]]≤2e−mπε2/12.
So P is within επ of π with probability ≥1−2e−mπε2/12;
this exceeds 1−δ once
m≥πε212ln(2/δ).
The (ε,δ)-approximation and FPRAS
Definition.X is an (ε,δ)-approximation of a value V if
Pr[∣X−V∣≤εV]≥1−δ.
(Relative error ≤ε with confidence ≥1−δ.)
Theorem (sample-size for estimation). Let X1,…,Xm be i.i.d. indicators with
mean μ=E[Xi]. If
m≥ε2μ3ln(2/δ),
then m1∑iXi is an (ε,δ)-approximation of μ.
Definition (FPRAS). A fully polynomial randomized approximation scheme for a
quantity V(X) is a randomized algorithm that, given input X and $0<\varepsilon,
\delta<1$, outputs an (ε,δ)-approximation of V(X) in time polynomial
in ∣X∣, 1/ε, and ln(1/δ).
The catch that drives everything. The sample size ε2μ3ln(2/δ)
blows up when μ is tiny. If the thing you’re estimating is an exponentially
small fraction of your sample space, naïve uniform sampling needs exponentially many
samples to ever see a success. “We need reasonable sampling” — a sample space where
the target is a non-negligible fraction. The art of counting via sampling is choosing
the right space. The next example shows the fix.
Case study — counting #DNF (the Karp–Luby coverage trick)
Problem #DNF. Given a DNF formula F=C1∨⋯∨Ct, count C(F) = the
number of satisfying assignments. (Note: DNF satisfiability is trivial — one clause
satisfiable; but counting solutions is #P-hard. Also F satisfiable $\iff #{\text{sat
assignments of }\neg F} < 2^n$.)
Naïve sampling fails. Draw α∈R{0,1}n, count fraction satisfying F,
scale by 2n. Estimator Y=(X/m)2n has E[Y]=C(F), and X/m is an
(ε,δ)-approximation of C(F)/2n once
m≥ε2C(F)3⋅2nln(2/δ).
If C(F)≥2n/α(n) for a polynomial α, this m is polynomial — fine. But
if C(F) is exponentially small, m is exponential. Hopeless in general.
The fix — sample from a smartly chosen space where success is dense. A clause Ci
with ℓ(i) literals has exactly2n−ℓ(i) satisfying assignments; call that set
SCi. Form the multiset unionU={(i,a)∣1≤i≤t,a∈SCi},∣U∣=i∑∣SCi∣=i∑2n−ℓ(i),
which is easy to compute and easy to sample from (pick clause i with probability
∣SCi∣/∣U∣, then a uniform satisfying assignment of Ci). The true count is the
size of the set union C(F)=∣⋃iSCi∣. The ratio
∣U∣C(F)=∑i∣SCi∣∣⋃iSCi∣≥t1
because each satisfying assignment is counted at most t times in U (it satisfies at
most t clauses). Success is now a ≥1/t fraction — polynomially dense!
Coverage estimator (Karp–Luby). Sample (i,a) uniformly from U. Count it as a
“success” iff i is the first clause that a satisfies (i.e.
a∈/⋃j<iSCj) — this picks exactly one representative per
satisfying assignment, so the success probability is exactly C(F)/∣U∣. Then
Y=(X/m)⋅∣U∣ estimates C(F).
Because the success probability is ≥1/t, the estimation theorem needs only
m=⌈ε23tln(2/δ)⌉
samples — polynomial. This yields an FPRAS for #DNF.
The lesson (professor-pleaser). You can’t estimate the size of a needle-in-a-haystack
set by uniform darts. Karp–Luby’s move: don’t sample the haystack — sample a slightly
larger, easy-to-handle space U in which the target is a ≥1/t fraction, then
correct for over-counting by keeping only the “first clause” representative. Reducing
a counting problem to sampling where the answer is dense is the master template of
approximate counting.
FPAUS — when even sampling is only approximate
Sometimes you cannot sample exactly from the target, only almost uniformly (this is
where MCMC re-enters: the chain only reaches ε-close to stationary).
Definition. A sampler A on space Ω generates an ε-uniform
sample if for all S⊆Ω, $;\bigl|\Pr[w\in S] - |S|/|\Omega|\bigr| \le
\varepsilon;$ (i.e. variation distance from uniform ≤ε). A FPAUS
(fully polynomial almost-uniform sampler) produces one in time polynomial in ∣X∣ and
ln(1/ε).
The grand connection. FPAUS ⇒ FPRAS for many self-reducible problems
(counting matchings, colourings, knapsack solutions, …): almost-uniform sampling can be
bootstrapped into approximate counting. And the FPAUS itself is built by MCMC —
design a rapidly mixing chain whose stationary distribution is (almost) uniform on
Ω (§7–§9), run it for the mixing time (§10–§12), read off the state. This closes
the entire loop of the lecture: build the chain (reversibility/Metropolis) → bound the
mixing time (coupling/eigenvalues) → sample → count.
The spine — one line per movement
Markov chain = memoryless random motion = a stochastic matrix P. A nice
(irreducible, finite, aperiodic) chain forgets its start and converges to a unique
stationary π (Fundamental Theorem; πi=1/hi,i). Stationarity is easiest
to verify and to engineer via detailed balance / reversibility $\pi_iP_{ij} =
\pi_jP_{ji}$. That gives a sampling machine (MCMC): design a chain whose stationary
distribution is the target σ (uniform via self-loops; arbitrary via
Metropolis–Hastings, using only probability ratios so the unknown normalizer
cancels), run it past its mixing time (variation distance ≤ε), read off
a sample. Mixing is bounded by coupling, strong uniform stopping times (card
shuffles: coupon collector ×2, birthday paradox), or the spectral gap (expanders mix
in O(logn) — and expander walks recycle random bits to amplify BPP with O(k)
bits). Finally, sampling becomes counting: (ε,δ)-approximation →
FPRAS, with #DNF (Karp–Luby coverage) as the model example, and FPAUS the bridge
from almost-uniform sampling back to approximate counting.
Theme
The one idea
Markov property
present screens off past from future; chain = matrix P
Fundamental Theorem
nice chain forgets its start → unique π; πi=1/hi,i
Reversibility
local pairwise balance πiPij=πjPji ⇒ stationary; the design lever
Random walk on graph
$\pi_v = \deg(v)/2
MCMC
invent a chain whose π = desired σ; sample by running it
Metropolis–Hastings
any prescribed π from ratios only — normalizer cancels
expansion ⇔ spectral gap ⇒ O(logn) mixing; BPP error in O(k) bits
FPRAS / #DNF
sample where the target is dense (Karp–Luby), then scale
Connections / threads to drill
Detailed balance = pairwise independence’s cousin in chain-land: a local condition
that buys a global property, exactly like §5’s “reversibility ⇒ stationary.”
Coupling and strong uniform stopping are the two universal mixing-time hammers —
be ready to state the Coupling Lemma and the stopping-time lemma and run the
coupon-collector card-shuffle analysis end-to-end.
Expander BPP amplification (O(k) bits, error 2−k) is the exam bridge between
this lecture and the complexity / derandomization block — “randomness is expensive;
recycle it.” Ties to Lecture 3’s error-reduction and Session 5’s “BPP=P?” thread.
Karp–Luby #DNF is the canonical “sample where the answer is dense” trick; the
(ε,δ)/FPRAS framework is the language of approximate counting.
The 2SAT/3SAT opener ties the chain’s drift directly to algorithm running time
(fair walk O(n2) vs. biased 2n) — links forward to Schöning’s derandomized k-SAT.
[ ] Be ready to state the Fundamental Theorem (all four parts + the two hypotheses
each pull their weight) and to derive πv=deg(v)/2∣E∣ via detailed balance.
[ ] Be ready to build a Metropolis chain for a given π (weighted IS) and explain
why the normalizer B cancels.
[ ] Be ready to run the expander-walk BPP amplification count of random bits
(n+O(k)) and say why correlated walk samples still give a Chernoff-like bound.