Fibonacci sequence explained step-by-step: recursion tree analysis, memoization (top-down), bottom-up dynamic programming, and O(1) space optimization.
The Fibonacci sequence (0, 1, 1, 2, 3, 5, 8, 13, 21, ...) is defined by the recurrence relation F(n) = F(n-1) + F(n-2) with base cases F(0) = 0 and F(1) = 1.
It serves as the introductory example for Dynamic Programming. Naive recursion computes identical subproblems repeatedly, exploding into an exponential O(2ⁿ) call tree. By caching intermediate results (top-down memoization) or computing iteratively from base cases up (bottom-up tabulation with two tracking variables), the time complexity drops to O(n) with strictly O(1) auxiliary memory.
Handle fundamental stopping conditions: F(0) = 0 and F(1) = 1 directly without recurring.
Store computed subproblem values in a lookup table or map. Whenever a branch requests F(k), return the cached value in O(1) time rather than re-evaluating the sub-tree.
Iterate sequentially from index 2 up to n using the relation dp[i] = dp[i-1] + dp[i-2], building solutions from the ground up.
Notice that calculating F(n) requires only the immediate two preceding values (F(n-1) and F(n-2)). Maintain two state variables (`prev1` and `prev2`) to achieve O(1) constant auxiliary space.
1// 1. Bottom-Up Tabulation with O(1) Constant Auxiliary Space2function fibonacci(n) {3 if (n <= 0) return 0;4 if (n === 1) return 1;5 6 let prev2 = 0; // F(0)7 let prev1 = 1; // F(1)8 let current = 0;9 10 for (let i = 2; i <= n; i++) {11 current = prev1 + prev2;12 prev2 = prev1;13 prev1 = current;14 }15 16 return current;17}18 19// 2. Top-Down Memoization (Linear O(n) Space for recursion stack & cache)20function fibMemo(n, memo = {}) {21 if (n <= 0) return 0;22 if (n === 1) return 1;23 if (memo[n] !== undefined) return memo[n];24 25 memo[n] = fibMemo(n - 1, memo) + fibMemo(n - 2, memo);26 return memo[n];27}28 29// Example usage:30// fibonacci(10); // 5531// fibMemo(10); // 55Play through every comparison, swap, and state change, adjust the speed, or enter custom inputs to test edge cases.
The full interactive roadmap is unlocking — these specialized modules land in upcoming releases.
This feature will be implemented in the next update.
This feature will be implemented in the next update.
This feature will be implemented in the next update.
Explore the full catalog — 30+ algorithms with more unlocking every release.
Overlapping subproblem memoization & DP table animator
Test your understanding of Fibonacci Series complexity and step mechanics.
Q1.What is the time complexity of naive recursive Fibonacci without memoization?
Q2.Why can bottom-up Fibonacci be calculated in O(1) auxiliary space?
Apply Fibonacci Series to real coding interview questions.
Find the number of distinct ways to climb n stairs taking 1 or 2 steps at a time.
Determine the maximum amount of money you can rob tonight without alerting adjacent houses.