Problem Statement
The Fibonacci Number problem is to compute the nth number in the Fibonacci sequence. The sequence starts with 0 and 1, and each subsequent number is the sum of the two preceding ones.
Algorithmic Approach / Logic
To solve this problem using dynamic programming, we can use an iterative approach to store previously computed Fibonacci numbers. This avoids the exponential time complexity associated with a naive recursive solution. The idea is to build up the solution incrementally by storing the results of subproblems in an array.
Code Implementation
def fibonacci(n):
if n <= 1:
return n
dp = [0] * (n + 1)
dp[0], dp[1] = 0, 1
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
In this implementation:
- Base case: If n is less than or equal to 1, return n.
- Create an array `dp` of size n + 1 and initialize the first two elements as 0 and 1.
- Iterate from 2 to n, filling in each element by summing the previous two elements in the array.
- Return the last element of the `dp` array, which contains the Fibonacci number at position n.
Complexity Analysis
The time complexity of this dynamic programming solution is O(n), where n is the input value. This is because we perform a single pass through the array to compute each Fibonacci number, and the space complexity is also O(n) due to the storage of intermediate results in the `dp` array.