Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

ML coding · Probabilistic models

Stationary distribution of a Markov chain

Easy · Target 12 minutes · Python and NumPy

Given a row-stochastic transition matrix P (n × n, each row sums to 1) of an irreducible, aperiodic Markov chain, return its stationary distribution π: the unique probability vector with πP = π.

Examples

Input P = [[0.9, 0.1], [0.5, 0.5]]

Output [0.8333, 0.1667]

A calm state that is sticky and a volatile one that is not: 5/6 of the time calm.

Input P = [[0, 1], [0.5, 0.5]]

Output [0.3333, 0.6667]

π = (1/3, 2/3). Check: (1/3)(0, 1) + (2/3)(0.5, 0.5) = (1/3, 2/3).

Input P = [[0.5, 0.25, 0.25], [0.25, 0.5, 0.25], [0.25, 0.25, 0.5]]

Output [0.3333, 0.3333, 0.3333]

A symmetric chain: uniform.

Constraints

  • 1 ≤ n ≤ 500
  • Rows sum to 1; the chain is irreducible and aperiodic
  • Checked to a relative tolerance of 10⁻⁹

Hints

Hint 1

πP = π is the same as (Pᵀ − I)πᵀ = 0. Why can you not just solve that system?

Hint 2

The n equations are linearly dependent, because the rows of P sum to 1. One of them carries no information.

Hint 3

Replace the last equation with Σπ = 1 (a row of ones, right-hand side 1) and call np.linalg.solve.

Where candidates go wrong

  • Solving (Pᵀ − I)π = 0 directly: the matrix is singular, and the only solution a solver finds is π = 0.
  • Using P instead of Pᵀ: that finds the right eigenvector, which is the all-ones vector.
  • Taking an eigenvector of Pᵀ for eigenvalue 1 and forgetting to normalise it, or its sign.
Console⌘/Ctrl + Enter runs

Python runs in your browser with NumPy. The first run downloads the runtime, which takes a few seconds.


Why interviewers ask it

Quant interviews ask for this in many disguises: the long-run fraction of days in a high-volatility regime, the share of time a queue is full, the probability a random walk on a graph is at a node. The coding version tests whether you see that the balance equations are dependent and know what to do about it.

The theory behind it is in the lesson Naive Bayes, EM, Viterbi and Markov chains from scratch.


Keep going