Fibonacci Sequence

Problem Statement

Return the nth Fibonacci number, where F(0)=0, F(1)=1, F(n)=F(n-1)+F(n-2).

Example: Input: n = 6 → Output: 8

Approach 1: Simple Recursion

Explanation: Directly apply the Fibonacci formula recursively.

Time Complexity: O(2ⁿ)

Space Complexity: O(n) (stack)

function fib(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    return fib(n-1) + fib(n-2)
      

Approach 2: Memoization (Top-Down DP)

Explanation: Store computed Fibonacci numbers to avoid recomputation.

Time Complexity: O(n)

Space Complexity: O(n) (stack + memo)

memo = {}
function fib(n):
    if n in memo:
        return memo[n]
    if n <= 1:
        return n
    memo[n] = fib(n-1) + fib(n-2)
    return memo[n]
      

Approach 3: Iterative / Bottom-Up

Explanation: Use a loop to calculate Fibonacci numbers sequentially.

Time Complexity: O(n)

Space Complexity: O(1)

a = 0, b = 1
for i from 2 to n:
    c = a + b
    a = b
    b = c
return b if n>0 else 0