LeetCode Problem Workspace
Fibonacci Number
Calculate the nth Fibonacci number using state transition dynamic programming and recursive techniques efficiently in interviews.
4
Topics
8
Code langs
3
Related
Practice Focus
Easy · State transition dynamic programming
Answer-first summary
Calculate the nth Fibonacci number using state transition dynamic programming and recursive techniques efficiently in interviews.
Ace coding interviews with Interview AiBoxInterview AiBox guidance for State transition dynamic programming
The Fibonacci Number problem is a classic example of state transition dynamic programming where each number depends on the sum of its two predecessors. The optimal solution combines recursion with memoization or iterative DP to avoid redundant calculations. Understanding the transition formula F(n) = F(n-1) + F(n-2) and managing base cases efficiently ensures fast computation even for larger n values.
Problem Statement
Given an integer n, compute the nth number in the Fibonacci sequence, where each number is the sum of the previous two numbers, starting from F(0) = 0 and F(1) = 1.
Implement a function that returns F(n). You may use recursion, memoization, or iterative dynamic programming, but must handle the sequence efficiently to avoid excessive redundant computations.
Examples
Example 1
Input: See original problem statement.
Output: See original problem statement.
F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n > 1.
Example 2
Input: n = 2
Output: 1
F(2) = F(1) + F(0) = 1 + 0 = 1.
Example 3
Input: n = 3
Output: 2
F(3) = F(2) + F(1) = 1 + 1 = 2.
Constraints
- 0 <= n <= 30
Solution Approach
Recursive Solution with Memoization
Implement a top-down recursive function storing intermediate results in a hash map or array. Base cases are F(0) = 0 and F(1) = 1. Each recursive call returns F(n-1) + F(n-2), caching results to avoid repeated work.
Iterative Dynamic Programming
Use a bottom-up approach by initializing an array of size n+1. Set dp[0] = 0, dp[1] = 1, then iterate from 2 to n, updating dp[i] = dp[i-1] + dp[i-2]. This avoids recursion overhead and uses O(n) time and space.
Space-Optimized Iterative Approach
Keep only two variables representing the last two Fibonacci numbers instead of a full array. Update them iteratively: prev = 0, curr = 1, then for i = 2 to n, compute next = prev + curr, update prev = curr, curr = next. This reduces space to O(1).
Complexity Analysis
| Metric | Value |
|---|---|
| Time | Depends on the final approach |
| Space | Depends on the final approach |
Time complexity depends on the approach: naive recursion is O(2^n), memoized recursion and iterative DP are O(n). Space complexity ranges from O(n) for DP array or memoization to O(1) for space-optimized iteration.
What Interviewers Usually Probe
- Expect correct handling of base cases F(0) and F(1).
- Check whether the candidate avoids redundant recursive calls using memoization.
- Watch for space optimization in iterative solutions for follow-up questions.
Common Pitfalls or Variants
Common pitfalls
- Naive recursion without memoization causes exponential time complexity and stack overflow for larger n.
- Incorrectly handling base cases leads to off-by-one errors in sequence values.
- Using unnecessary extra space when a simple two-variable iteration suffices.
Follow-up variants
- Compute Fibonacci modulo 10^9+7 to test large n handling and modular arithmetic.
- Return the first n Fibonacci numbers as an array to test iterative DP comprehension.
- Implement a recursive Fibonacci with limited stack depth using tail recursion to explore optimization.
FAQ
What is the Fibonacci Number problem pattern?
It follows a state transition dynamic programming pattern where F(n) = F(n-1) + F(n-2).
Can I solve Fibonacci Number with plain recursion?
Yes, but naive recursion has O(2^n) time complexity and will fail for larger n without memoization.
How do I optimize Fibonacci Number computation?
Use iterative DP or memoization to reduce time complexity to O(n) and consider two-variable iteration to reduce space to O(1).
What are common mistakes in Fibonacci Number interviews?
Common mistakes include missing base cases, redundant recursion, and overusing space for simple iterative solutions.
Is memoization always better than iterative for Fibonacci Number?
Memoization helps clarify recursion logic, but iterative DP is often faster and uses less space, making it more efficient for large n.
Solution
Solution 1: Recurrence
We define two variables $a$ and $b$, initially $a = 0$ and $b = 1$.
class Solution:
def fib(self, n: int) -> int:
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return aSolution 2: Matrix Exponentiation
We define $\textit{Fib}(n)$ as a $1 \times 2$ matrix $\begin{bmatrix} F_n & F_{n - 1} \end{bmatrix}$, where $F_n$ and $F_{n - 1}$ are the $n$-th and $(n - 1)$-th Fibonacci numbers, respectively.
class Solution:
def fib(self, n: int) -> int:
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return aContinue Practicing
Continue Topic
math
Practice more edge cases under the same topic.
arrow_forwardauto_awesomeContinue Pattern
State transition dynamic programming
Expand the same solving frame across more problems.
arrow_forwardsignal_cellular_altSame Difficulty Track
Easy
Stay on this level to stabilize interview delivery.
arrow_forward