ObjectiveMCQ
Print Protected
This page is protected for print. Use the website to view the content.
Analyze the following two implementations of Fibonacci sequence and answer: What is the time complexity difference?
Implementation 1: Recursive
def fib_recursive(n):
if n <= 1:
return n
return fib_recursive(n-1) + fib_recursive(n-2)
Implementation 2: Dynamic Programming
def fib_dp(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]

For , which statement is most accurate?
Correct Answer: B — B: Recursive is $O(2^n)$, DP is $O(n)$ - DP is exponentially faster
The recursive version has exponential time complexity because:
Recurrence relation:
Solving this gives: where (golden ratio)
For practical purposes:
The DP version has linear time complexity because:
Performance Comparison for n=40:
Space Complexity:
Optimization Note: DP can be further optimized to space by keeping only last two values:
def fib_optimized(n):
if n <= 1:
return n
prev, curr = 0, 1
for _ in range(2, n + 1):
prev, curr = curr, prev + curr
return curr
Conclusion: DP is exponentially faster than naive recursion for Fibonacci.