When a DP’s transition is linear and the same at every step, the whole DP is a matrix, and steps become one matrix power — instead of . This is what makes tractable.
The condition
Your recurrence must be expressible as
with a constant matrix . Then , computable by binary exponentiation on matrices.
If depends on , this fails — unless the dependence is periodic, in which case multiply one period’s matrices together and exponentiate that.
Building the matrix
Fibonacci.
General linear recurrence : the companion matrix
Adding a constant term : extend the vector with a permanent 1.
Prefix sums : add a row for .
Polynomial terms : extend with and encode the binomial updates .
Code
using Mat = vector<vector<long long>>;
const long long MOD = 1e9 + 7;
Mat mul(const Mat& a, const Mat& b) {
int n = a.size(), m = b[0].size(), K = b.size();
Mat c(n, vector<long long>(m, 0));
for (int i = 0; i < n; i++)
for (int k = 0; k < K; k++) {
if (!a[i][k]) continue;
for (int j = 0; j < m; j++)
c[i][j] = (c[i][j] + a[i][k] * b[k][j]) % MOD;
}
return c;
}
Mat power(Mat a, long long e) {
int n = a.size();
Mat r(n, vector<long long>(n, 0));
for (int i = 0; i < n; i++) r[i][i] = 1;
while (e) { if (e & 1) r = mul(r, a); a = mul(a, a); e >>= 1; }
return r;
}The if (!a[i][k]) continue; and the loop order together give a 3-5× speedup over the naive version — the inner loop then walks both b and c sequentially.
Where it applies
| Problem | Matrix size |
|---|---|
| Linear recurrence of order | |
| Count walks of length in a graph | — the adjacency matrix |
| Count strings of length avoiding a pattern | states of the Aho-Corasick automaton |
| Count strings with a forbidden substring | KMP automaton states |
| Tilings of a board | over profile masks |
| Markov chain after steps | state count |
| DP over a small state set, huge | number of states |
| Shortest path with exactly edges | in the min-plus semiring |
The min-plus semiring
Replace with in the matrix multiplication and the same exponentiation computes shortest paths using exactly edges:
c[i][j] = min(c[i][j], a[i][k] + b[k][j]);. This is how “cheapest route with exactly flights” problems are solved for up to .
Beating
For a linear recurrence of order , you do not need the full matrix:
| Method | Time |
|---|---|
| Matrix exponentiation | |
| Kitamasa | |
| Bostan-Mori |
All three compute where is the characteristic polynomial; they differ only in how fast the polynomial multiplication is. For and , matrix exponentiation is operations and Kitamasa is .
If you have the sequence but not the recurrence, Berlekamp-Massey recovers it from the first terms — a powerful combination: compute a few terms by brute force, find the recurrence automatically, then jump to term .
See also: Matrix Exponentiation · Kitamasa · Berlekamp-Massey