DSAverse
Recursion
Loading Recursion Visualizer...
Recursion Tree
depth: 1f(n) = f(n-1) + f(n-2)
Initializing Sorting Algorithms...
Sorting
Trees
Graphs
Preparing interactive visualizations...
Recursion
Loading Recursion Visualizer...
Recursion Tree
depth: 1f(n) = f(n-1) + f(n-2)
Compare naive recursion's explosive growth with memoization's dramatic efficiency — same result, radically fewer calls.
Click Play to begin.
Why is naive Fibonacci O(2^n) time complexity?
Click Play to see the call tree
Color Legend
def fibonacci_naive(n):
if n <= 1:
return n
return fibonacci_naive(n-1) + fibonacci_naive(n-2)
def fibonacci_memo(n, memo={}):
if n in memo:
return memo[n] # Cache hit!
if n <= 1:
memo[n] = n
return n
memo[n] = fibonacci_memo(n-1, memo) + fibonacci_memo(n-2, memo)
return memo[n]
# fib(5) = 5
# Naive calls: 15 vs Memoized: 6function fibNaive(n) {
if (n <= 1) return n;
return fibNaive(n-1) + fibNaive(n-2);
}
function fibMemo(n, memo = {}) {
if (n in memo) return memo[n];
if (n <= 1) { memo[n] = n; return n; }
memo[n] = fibMemo(n-1, memo) + fibMemo(n-2, memo);
return memo[n];
}
// fib(5) = 5