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
Bottom-up DP with two variables: start with a=F(0), b=F(1). For each step, compute c=a+b, shift a=b, b=c.
Time O(n), Space O(1).
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.
