Fibonacci Number
The Fibonacci sequence is defined as:F(0) = 0, F(1) = 1, and for n > 1, F(n) = F(n-1) + F(n-2). Given n, calculate F(n). This is the simplest example of a dynamic programming recurrence relation, where each value depends on the two previous values.
A recursive solution without memoization has exponential time O(2^n) because it recomputes the same subproblems repeatedly. Dynamic programming stores computed values to avoid redundant work. Using a bottom-up approach, we can compute F(0), F(1), F(2), and so on up to F(n) in O(n) time.
The space can be optimized to O(1) by noting that only the two most recent values are needed at each step. Use two variables to track F(n-1) and F(n-2), updating them iteratively. This eliminates the need for an array of size n.
Edge cases include n = 0 (return 0), n = 1 (return 1), and large n where the result may exceed 32-bit integers. In languages with fixed-width integers, use 64-bit or handle overflow.
The Fibonacci sequence appears throughout computer science and nature, from branching patterns in trees to the golden ratio. Solving it with DP demonstrates the core principles of memoization and tabulation — reusing computed subproblem results to avoid exponential blowup.
Example Input & Output
F(3) = F(2)+F(1) = 1+1 = 2.
F(4) = F(3)+F(2) = 2+1 = 3.
F(0) = 0.
F(2) = F(1)+F(0) = 1+0 = 1.
F(5) = F(4)+F(3) = 3+2 = 5.
Algorithm Flow
Solution Approach
Use recursion with memoization to calculate the nth Fibonacci number. The Fibonacci sequence is defined as fib(0)=0, fib(1)=1, and fib(n)=fib(n-1)+fib(n-2) for n>1. A naive recursive approach recalculates the same values many times, so memoization stores previously computed results in an array to avoid redundant work.
This iterative bottom-up approach builds the Fibonacci sequence from the base cases upward, storing each value exactly once. It avoids the exponential time complexity of naive recursion by solving each subproblem in order.
Time complexity is O(n), space complexity is O(n) for the memo array. A further optimization uses O(1) space by keeping only the last two values.
Best Answers
class Solution {
public int solution(int n) {
if (n <= 1) return n;
int a = 0, b = 1;
for (int i = 2; i <= n; i++) {
int c = a + b;
a = b;
b = c;
}
return b;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
