Matrix Power and Empirical Transitions for a Markov Chain
Math & Bit ManipulationAuto-graded · 14 test casesLast updated
Raise a row-stochastic matrix to a given power and build a row-normalized transition estimate from observed index pairs, leaving rows with no data as zeros.
A system moves between n states numbered 0 to n - 1. Its behavior is described by a one-step transition matrix, where transition_matrix[i][j] is the probability of moving from state i to state j in one step. Rows are "from" states and columns are "to" states.
Write a function that does two independent things and returns both results.
1. Multi-step probabilities. Compute the matrix M = transition_matrix raised to the power steps (ordinary matrix product, rows times columns). Entry M[i][j] is the probability of being in state j exactly steps steps after being in state i. When steps is 0, the result is the identity matrix.
2. Empirical estimate. observed_pairs is a list of [source, destination] pairs, each recording one observed move between states. Build an n x n count matrix where counts[s][d] is the number of times the pair [s, d] appears. Then divide each row by its own sum, so that the entry is the fraction of moves out of state s that went to state d. If a row has no observed moves (its sum is 0), the whole estimated row is 0.0 for every column. Do not apply smoothing, self-loops, or any other fill-in.
Return value: a dictionary with exactly two keys:
"multi_step": then x nmatrix from part 1, as a list of lists of numbers."estimated": then x nmatrix from part 2, as a list of lists of floats.
Small floating-point rounding differences are expected, since the values are real numbers produced by repeated multiplication.
Constraints
1 <= n <= 20, wheren = len(transition_matrix); the matrix is square.- Each entry of
transition_matrixis between0and1, and each row sums to1. 0 <= steps <= 10^9.0 <= len(observed_pairs) <= 10^5.- Every state index in
observed_pairsis an integer in[0, n - 1].
Examples
Example 1
Input: markov_power_and_estimate([[0.8, 0.2], [0.1, 0.9]], 2, [[0, 0], [0, 1], [0, 1], [1, 1], [1, 0]])
Output: {'multi_step': [[0.6600000000000001, 0.3400000000000001], [0.17000000000000004, 0.8300000000000001]], 'estimated': [[0.3333333333333333, 0.6666666666666666], [0.5, 0.5]]}
Example 2
Input: markov_power_and_estimate([[1, 0], [0, 1]], 0, [])
Output: {'multi_step': [[1, 0], [0, 1]], 'estimated': [[0, 0], [0, 0]]}
Hints
Hint 1
Matrix multiplication is associative, so you can compute the power by exponentiation by squaring instead of multiplying `steps` times. Start from the identity matrix.
Hint 2
For the estimate, first tally a count matrix from the pairs, then divide each row by its own total. Rows are the source states, so never normalize columns.
Hint 3
A row whose total is zero would cause a division by zero. Check for that case and emit a row of `0.0` values instead.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The two parts are independent.
Multi-step probabilities. By the Chapman-Kolmogorov relation, the probability of going from i to j in two steps is the sum over intermediate states m of P[i][m] * P[m][j]. That is exactly entry (i, j) of P * P. By induction, the k-step probabilities are the entries of P^k. To avoid steps separate multiplications, use exponentiation by squaring. Keep a running result (initially the identity) and a base (initially P). For each bit of steps, multiply result by base if the bit is set, then square base. With steps = 0 the loop never runs and the identity is returned, which is the correct "stay where you are" answer.
Empirical estimate. Tally how many times each [source, destination] pair appears into an n x n count matrix. The maximum-likelihood estimate of a transition probability is the count divided by the total number of moves leaving that source, so each row is divided by its own sum. A source that never appears has a row sum of zero, which would be a division by zero, so the rule in the statement applies: that row is all zeros.
Why it is correct
Matrix multiplication is associative, so grouping the product by binary digits of steps gives the same matrix as steps sequential multiplications. Row normalization of counts gives the fraction of outgoing moves from each state going to each destination, and the zero-total case is handled explicitly.
Complexity
- Matrix power:
O(n^3 log steps)time,O(n^2)space. - Counting and normalizing:
O(m + n^2)time formpairs,O(n^2)space.
Reference solution
from typing import Dict, List
def markov_power_and_estimate(transition_matrix: List[List[float]], steps: int, observed_pairs: List[List[int]]) -> Dict:
n = len(transition_matrix)
def multiply(a, b):
return [
[sum(a[i][k] * b[k][j] for k in range(n)) for j in range(n)]
for i in range(n)
]
# Exponentiation by squaring, starting from the identity matrix.
result = [[float(i == j) for j in range(n)] for i in range(n)]
base = [row[:] for row in transition_matrix]
exponent = steps
while exponent:
if exponent & 1:
result = multiply(result, base)
base = multiply(base, base)
exponent >>= 1
# Count observed transitions.
counts = [[0] * n for _ in range(n)]
for source, destination in observed_pairs:
counts[source][destination] += 1
# Normalize each row; rows with no data stay all zeros.
estimated = []
for row in counts:
total = sum(row)
estimated.append([c / total for c in row] if total else [0.0] * n)
return {"multi_step": result, "estimated": estimated}