Matrix Exponentiation
O(k³ log n)
Express the recurrence as a matrix and raise it to the n-th power by fast exponentiation.
0%
mastery
0/8 solved
0/8 solved
Recognise it
The signal
Small linear recurrence at a huge index (n ~ 1e18), walks of length exactly n, or constant-size DP state with the same transition each step.
1Brute force
Iterate the DP n times.
2The observation
n iterations of the same linear transition: binary exponentiation of the transition matrix.
3Why it works
M^n applied to the base vector gives the state after n steps.
Reach for it when
- +number of walks of length exactly n
- +DP with constant-size state and same transition every step
Not when
- ×Transition changes with iuse Plain DP
- ×Transitions are non-linear (min-plus/max-plus semirings still work)use Plain DP or another method
- ×n is moderate (e.g. 5000)use Plain DP is enough
Practice
0/8 solved
- Fibonacci NumberFoundationFoundationAdobe, AmazonEasy
- Fibonacci NumbersApply it · n = 1e18.Apply itCSESMedium
- Throwing DiceOne change · Recurrence with 6 terms.One changeCSESMedium
- Knight DialerTwists · Transition graph between digits.TwistsMedium
- Graph Paths IBranches · Walks of length k.BranchesCSESMedium
- Graph Paths IIMastery checkMastery checkCSESMedium
- Counting LCM ArraysCSESHard
- String Transformation by Rotations in Exactly k StepsSnowflakeOAHard
Go deeper1 combinations · resources
Combinations
Matrix Exponentiation+1D / Fibonacci-style
count sequences of length n with a fixed small automaton
- Matrix Exponentiation:
- applies it n times in O(k^3 log n)
- 1D / Fibonacci-style:
- defines a constant-size linear transition