Solving the Fibonacci sequence efficiently is a classic problem in computer science. The naive recursive approach has exponential time complexity due to repeated calculations, but there are several optimized methods to compute Fibonacci numbers with better performance. Here are the most efficient approaches:
1. Dynamic Programming (Memoization)
Store previously computed Fibonacci numbers to avoid redundant calculations.
Python Implementation:
def fibonacci_memoization(n, memo={}):
if n in memo:
return memo[n]
if n <= 1:
return n
memo[n] = fibonacci_memoization(n - 1, memo) + fibonacci_memoization(n - 2, memo)
return memo[n]
Time Complexity: (O(n))
Space Complexity: (O(n)) (due to recursion stack and memoization dictionary)
2. Dynamic Programming (Tabulation)
Use an iterative approach to build the Fibonacci sequence bottom-up.
Python Implementation:
def fibonacci_tabulation(n):
if n <= 1:
return n
dp = [0] * (n + 1)
dp[1] = 1
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
Time Complexity: (O(n))
Space Complexity: (O(n))
3. Space-Optimized Iterative Approach
Reduce space complexity to (O(1)) by only storing the last two Fibonacci numbers.
Python Implementation:
def fibonacci_iterative(n):
if n <= 1:
return n
a, b = 0, 1
for _ in range(2, n + 1):
a, b = b, a + b
return b
Time Complexity: (O(n))
Space Complexity: (O(1))
4. Matrix Exponentiation (Fast Doubling)
Use matrix exponentiation to compute Fibonacci numbers in (O(\log n)) time.
Python Implementation:
def matrix_mult(A, B):
return [
[A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0][0] * B[0][1] + A[0][1] * B[1][1]],
[A[1][0] * B[0][0] + A[1][1] * B[1][0], A[1][0] * B[0][1] + A[1][1] * B[1][1]]
]
def matrix_pow(matrix, n):
result = [[1, 0], [0, 1]] # Identity matrix
base = matrix
while n > 0:
if n % 2 == 1:
result = matrix_mult(result, base)
base = matrix_mult(base, base)
n //= 2
return result
def fibonacci_matrix(n):
if n <= 1:
return n
F = [[1, 1], [1, 0]]
result = matrix_pow(F, n - 1)
return result[0][0]
Time Complexity: (O(\log n))
Space Complexity: (O(\log n))
5. Closed-Form Expression (Binet's Formula)
Use Binet's formula for a direct computation, but be cautious of floating-point precision issues for large (n).
Python Implementation:
import math
def fibonacci_binet(n):
sqrt_5 = math.sqrt(5)
phi = (1 + sqrt_5) / 2
return round((phi**n - (-1/phi)**n) / sqrt_5)
Time Complexity: (O(1))
Space Complexity: (O(1))
Note: Not suitable for large (n) due to precision loss.
Recommendation
For most practical purposes, the space-optimized iterative approach is the best choice due to its simplicity, efficiency, and lack of recursion overhead. If you need to compute very large Fibonacci numbers, consider the matrix exponentiation method.