Algorithms · Visualized
DP: Fibonacci (Tabulation)
Dynamic Programming
Break problems into overlapping subproblems and store answers.
Computes the Fibonacci sequence bottom-up, building an array of results from the smallest subproblems up to the target, rather than recursing top-down. Time: O(n) average, O(n) worst; space: O(n), reducible to O(1) by only keeping the last two values.
Big-O: The most-asked interview category — 35 classics here.
Fibonacci (Tabulation)
Dynamic ProgrammingComputes the Fibonacci sequence bottom-up, building an array of results from the smallest subproblems up to the target, rather than recursing top-down. This 'tabulation' approach avoids recursion overhead entirely and is the classic alternative to memoized (top-down) Fibonacci.
How Fibonacci (Tabulation) Works
- Create an array (or just two variables) to hold Fibonacci values, with base cases dp[0]=0 and dp[1]=1.
- Loop from i=2 up to n.
- At each step, compute dp[i] = dp[i-1] + dp[i-2] using the two previously computed values.
- Continue filling the table until you reach index n.
- Return dp[n] as the final answer.
Fibonacci (Tabulation) Worked Example
Input: 6
dp[0]=0, dp[1]=1. dp[2]=1+0=1. dp[3]=1+1=2. dp[4]=2+1=3. dp[5]=3+2=5. dp[6]=5+3=8. fib(6)=8.
| 0 | 1 | |
|---|---|---|
| dp | 0 | 1 |
def fibonacci(n):
if n < 2:
return n
a, b = 0, 1
for _ in range(2, n + 1):
a, b = b, a + b
return bBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Fibonacci (Tabulation) Time & Space Complexity
When to Use Fibonacci (Tabulation)
- Teaching bottom-up DP as an alternative to top-down memoization — no recursion overhead and easy to optimize to O(1) space.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.