Matrix Exponentiation
Raise a matrix to the n-th power in O(log n) multiplications instead of n — the trick that computes the billionth Fibonacci number or counts length-n walks in a graph almost instantly. It’s fast exponentiation, lifted from numbers to matrices. Solve it in Python or TypeScript, with hidden tests.
The problem
Implement matrix_power(mat, power): given a square integer matrix mat (a list of rows) and a non-negative integer power, return mat raised to that power (matrix multiplication, not element-wise). power = 0 returns the identity matrix. Use binary (fast) exponentiation to do it in O(log power) matrix multiplies.
mat = [[1,1],[1,0]], power = 10[[89, 55], [55, 34]]mat = [[2,0],[0,2]], power = 3[[8, 0], [0, 8]]- The matrix is square (n×n) with integer entries; use exact integer arithmetic.
power = 0→ the identity matrix (1 on the diagonal, 0 elsewhere).- Use fast exponentiation: square the base and halve the exponent, multiplying into the result when the current bit is set — O(log power) multiplies.
Your turn — write it
Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are right above and Reveal solution is one click away.
Implement matrix_power(mat, power): write a helper that multiplies two n×n matrices, start the result at the identity, then loop — if the low bit of power is set, multiply the result by the current base; then square the base and shift power right.
- First write
matmul(A, B): entry[i][j]is the dot product of rowiof A with columnjof B. - Initialise the result as the identity matrix so that "multiply into result" starts correctly.
- Fast exponentiation: while
power > 0, ifpoweris odd multiplyresult *= base; thenbase *= baseandpower //= 2. - This turns n multiplications into about log₂(n) — the same idea as fast exponentiation of plain numbers.
Explore the topic
See this challenge alongside everything else on the same subject — handbooks, system designs, algorithms and tools, in one place.