Problem Description
Given a non-negative integer n, calculate F(n) where F(n) represents the nth Fibonacci number. The Fibonacci sequence is defined as follows: F(0) = 0, F(1) = 1, and F(n) = F(n - 1) + F(n - 2) for n > 1.
Key Insights
- The Fibonacci sequence is defined recursively.
- A direct recursive solution can lead to redundant calculations.
- An iterative or dynamic programming (DP) approach can efficiently compute the result.
- For n in the range [0, 30], an iterative solution with O(n) time complexity is both simple and effective.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Solution
We solve the problem using an iterative approach which computes the Fibonacci numbers starting from 0 and 1 and then iteratively builds up to F(n). This method uses constant space by only keeping track of the last two computed Fibonacci values. The algorithm is efficient and avoids the pitfalls of recursive stack overflow or repeated calculations that would result from a naive recursion.