#509

Fibonacci Number

Easy
MathDynamic ProgrammingRecursionMemoizationDynamic ProgrammingRecursion
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses dynamic programming to store previously computed Fibonacci numbers, avoiding redundant calculations. This significantly reduces the number of recursive calls.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create an array to store Fibonacci numbers up to n.
  2. 2Step 2: Initialize the first two values: F(0) = 0 and F(1) = 1.
  3. 3Step 3: Use a loop to fill in the array from F(2) to F(n) using the relation F(n) = F(n-1) + F(n-2).
  4. 4Step 4: Return the value at index n.
solution.py8 lines
1def fib(n):
2    if n == 0:
3        return 0
4    fibs = [0] * (n + 1)
5    fibs[1] = 1
6    for i in range(2, n + 1):
7        fibs[i] = fibs[i - 1] + fibs[i - 2]
8    return fibs[n]

Complexity note: The time complexity is O(n) because we compute each Fibonacci number once. The space complexity is O(n) due to the storage of the Fibonacci numbers in an array.

  • 1Recursive definitions can lead to exponential time complexity if not optimized.
  • 2Dynamic programming can significantly reduce redundant calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.