Fibonacci Number
Compute the n-th Fibonacci number using top-down recursion with memoization to eliminate exponential duplicate calculations.
01The problem
The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is:
F(0) = 0, F(1) = 1F(n) = F(n - 1) + F(n - 2), forn > 1.
Given n, calculate F(n).
| Input | Output | Why |
|---|---|---|
n = 2 | 1 | F(2) = F(1) + F(0) = 1 + 0 = 1 |
n = 3 | 2 | F(3) = F(2) + F(1) = 1 + 1 = 2 |
n = 4 | 3 | F(4) = F(3) + F(2) = 2 + 1 = 3 |
Constraints: 0 <= n <= 30.
02How to spot it
- The problem statement provides the exact recurrence relation:
F(n) = F(n - 1) + F(n - 2). - Base cases are explicitly given:
F(0) = 0,F(1) = 1. - A naive recursive tree recomputes identical values repeatedly (e.g.
F(3)is computed multiple times when evaluatingF(5)). - Adding a lookup cache (memoization) ensures each
F(k)is evaluated only once.
So: recursion with memoization.
03Pseudocode
fib(n):
if n <= 1: return n
if n in memo: return memo[n]
memo[n] = fib(n-1) + fib(n-2)
return memo[n]- Base cases: return
0for0and1for1. - Check memo: if already computed, return the cached result.
- Compute
fib(n-1) + fib(n-2), store in memo, and return it.
04Watch it work
current n
5
memo map
status
start
Compute F(5) using top-down recursion with memoization.
Pseudocode
- fib(n):
- if n <= 1: return n
- if n in memo: return memo[n]
- memo[n] = fib(n-1) + fib(n-2)
- return memo[n]
Variables
- n
- 5
05Step-by-step dry run
- 1
current n
5
memo map
emptystatus
start
Compute F(5) using top-down recursion with memoization.
n = 5
- 2
current n
5
memo map
emptystatus
calling F(4) and F(3)
Computing F(5) = F(4) + F(3).
k = 5
- 3
current n
4
memo map
emptystatus
calling F(3) and F(2)
Computing F(4) = F(3) + F(2).
k = 4
- 4
current n
3
memo map
emptystatus
calling F(2) and F(1)
Computing F(3) = F(2) + F(1).
k = 3
- 5
current n
2
memo map
emptystatus
calling F(1) and F(0)
Computing F(2) = F(1) + F(0).
k = 2
- 6
current n
1
memo map
emptystatus
base case F(1)=1
Base case reached: F(1) = 1.
k = 1result = 1
- 7
current n
0
memo map
emptystatus
base case F(0)=0
Base case reached: F(0) = 0.
k = 0result = 0
- 8
current n
2
memo map
2 → 1status
memo[2]=1
Stored memo[2] = 1. Return 1.
k = 2ans = 1
- 9
current n
1
memo map
2 → 1status
base case F(1)=1
Base case reached: F(1) = 1.
k = 1result = 1
- 10
current n
3
memo map
2 → 13 → 2status
memo[3]=2
Stored memo[3] = 2. Return 2.
k = 3ans = 2
- 11
current n
2
memo map
2 → 13 → 2status
memo hit F(2)=1
Memo hit! F(2) was already computed as 1. Return cached value.
k = 2cached = 1
- 12
current n
4
memo map
2 → 13 → 24 → 3status
memo[4]=3
Stored memo[4] = 3. Return 3.
k = 4ans = 3
- 13
current n
3
memo map
2 → 13 → 24 → 3status
memo hit F(3)=2
Memo hit! F(3) was already computed as 2. Return cached value.
k = 3cached = 2
- 14
current n
5
memo map
2 → 13 → 24 → 35 → 5status
memo[5]=5
Stored memo[5] = 5. Return 5.
k = 5ans = 5
- 15
result F(n)
5
memo map
2 → 13 → 24 → 35 → 5Completed: F(5) = 5.
result = 5
06Java solution
import java.util.HashMap;
import java.util.Map;
public class FibonacciNumber {
private static final Map<Integer, Integer> memo = new HashMap<>();
public static int fib(int n) {
if (n <= 1) return n;
if (memo.containsKey(n)) return memo.get(n);
int ans = fib(n - 1) + fib(n - 2);
memo.put(n, ans);
return ans;
}
public static void main(String[] args) {
System.out.println(fib(2));
System.out.println(fib(3));
System.out.println(fib(4));
System.out.println(fib(5));
}
}1 2 3 5
07Why it works
Without memoization, the call tree branches in two at every step, creating O(2^n) total calls.
By storing memo.put(n, ans) before returning, subsequent calls for the same value n take O(1) time.
Because there are only n + 1 unique subproblems (F(0) through F(n)), the recursion tree collapses into a linear chain of n evaluations.
08Time and space
- Time complexity:
O(n). Each state from0tonis computed once. - Space complexity:
O(n). The call stack reaches depthn, and the memo map storesnkeys.
09Edge cases
n = 0: Immediately hits base caseif (n <= 1) return n, returns0.n = 1: Immediately hits base case, returns1.n = 30(constraint upper bound): Computes smoothly in milliseconds without integer overflow.
10Common mistakes
- Omitting memoization. Running raw recursion takes
O(2^30) ≈ 10^9operations, which risks timing out or causing unnecessary CPU churn. - Using 0 as unvisited marker in a memo array. If using
int[] memo,F(0) = 0could be mistaken for an unvisited entry. Either initialize with-1or useif (n <= 1) return nas a guard before array lookup.
11Other approaches
| Approach | Time | Space | Notes |
|---|---|---|---|
| Naive recursion | O(2^n) | O(n) stack | Too slow, repeated work |
| Top-down memoization | O(n) | O(n) | Classic recursive lesson |
| Bottom-up DP | O(n) | O(1) space | Two variables a and b |
12In the interview
13Check your understanding
Quiz · 2 questions
0 of 2 answered
1. Why does naive recursion for Fibonacci have O(2^n) time complexity?
2. How many distinct subproblems exist when computing F(n)?
14Solve it yourself
Try implementing the matrix exponentiation approach for Fibonacci:
[[1, 1], [1, 0]]^n = [[F(n+1), F(n)], [F(n), F(n-1)]].- Can you compute
F(n)inO(log n)time using repeated squaring?