Overview
Matrix operations are essential for solving linear recurrences, graph problems, and optimization tasks. Matrix exponentiation can reduce O(n) dynamic programming to O(log n).Basic Matrix Structure
Simple Matrix (Compressed)
Full Matrix Class
Matrix Exponentiation
Fast exponentiation for matrices enables solving linear recurrences efficiently.Applications
1. Fibonacci Numbers
Compute F(n) in O(log n) time.Why This Works
Why This Works
The recurrence F(n) = F(n-1) + F(n-2) can be written as:Therefore:Since F(1) = 1 and F(0) = 0:The result is in the top-left element of the matrix power.
2. Generic Linear Recurrence
Solve recurrences of the form:3. Graph Problems
Count Paths of Length k
4. Dynamic Programming Acceleration
Many DP problems with linear transitions can be optimized:Matrix Properties
Determinant (Gaussian Elimination)
Matrix Transposition
Contest Examples
Example 1: Domino Tiling
Example 2: Grid Coloring
Example 3: Shortest Path with Exactly k Edges
Complexity Analysis
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| Matrix Addition | O(n²) | O(n²) |
| Matrix Multiplication | O(n³) | O(n²) |
| Matrix Exponentiation | O(n³ log k) | O(n²) |
| Determinant | O(n³) | O(n²) |
| Transpose | O(n²) | O(n²) |
Advanced Topics
Strassen’s Algorithm
Multiplies two n×n matrices in O(n^2.807) time using divide-and-conquer. Not commonly used in competitive programming due to large constants.Sparse Matrices
For matrices with mostly zeros, use sparse representations:Matrix Inverse (Gauss-Jordan)
Tips for Contests
- Always use modular arithmetic when the problem asks for result mod 10^9+7
- Check matrix dimensions before multiplication (n×m times m×p)
- Use fast exponentiation for computing large powers
- Initialize identity matrix correctly for matrix power
- Consider sparse representation for large matrices with few non-zero elements