Matrix Exponentiation - Problem

Given a positive integer n, compute the Nth Fibonacci number using matrix exponentiation in O(log n) time complexity.

The Fibonacci sequence is defined as:

  • F(0) = 0
  • F(1) = 1
  • F(n) = F(n-1) + F(n-2) for n ≥ 2

Your task is to implement an efficient solution that can handle large values of n by using matrix exponentiation instead of the naive recursive or iterative approaches.

Key insight: The Fibonacci recurrence can be represented as matrix multiplication, and we can use fast matrix exponentiation to achieve logarithmic time complexity.

Input & Output

Example 1 — Small Fibonacci Number
$ Input: n = 5
Output: 5
💡 Note: F(5) = F(4) + F(3) = 3 + 2 = 5. The sequence: F(0)=0, F(1)=1, F(2)=1, F(3)=2, F(4)=3, F(5)=5
Example 2 — Base Cases
$ Input: n = 0
Output: 0
💡 Note: F(0) = 0 by definition, this is the first Fibonacci number
Example 3 — Larger Fibonacci Number
$ Input: n = 10
Output: 55
💡 Note: F(10) = 55. Matrix exponentiation computes this efficiently in O(log 10) time instead of O(10) linear time

Constraints

  • 0 ≤ n ≤ 50
  • n is a non-negative integer

Visualization

Tap to expand
INPUTn = 8Find F(8) efficientlyProblem:Compute 8thFibonacci numberTraditional: O(n) timeGoal: O(log n) timeALGORITHM1Base matrix T = [[1,1],[1,0]]2Compute T^8 using binary exp38 = 1000₂ --> 3 squaring steps4Extract F(8) from result matrixBinary Steps:T^1 --> T^2 --> T^4 --> T^8Only 3 operations!RESULTFinal Matrix:[[34, 21], [21, 13]]F(8) = 21✓ Correct!Sequence verification:0,1,1,2,3,5,8,13,21Time: O(log 8) = O(3)Key Insight:Matrix exponentiation transforms the linear Fibonacci recurrence into logarithmicmatrix powers, reducing O(n) sequential steps to O(log n) binary operations.TutorialsPoint - Matrix Exponentiation | Fast Fibonacci Computation
Asked in
Google 25 Facebook 18 Microsoft 15 Amazon 12
25.0K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen