Algorithms

Recursion & Fibonacci

Visualize the recursive call tree for Fibonacci numbers and toggle memoization. The comparison makes overlapping subproblems obvious.

6 minLevel 2/3The interactive stage stays ad-free.
Calls1 / 25Cache hits0Naive calls25Memo calls11Calls saved14Unique subproblems7
6
Call stackfib(6)

Without memoization, fib(n) recomputes the same subproblems again and again. Turn on memoization and watch the call tree collapse: amber nodes are cache hits, and the call-stack chips show the current recursion path. Compare Naive calls with Memo calls above.

What you are seeing

1

Each node is a function call. A call to fib(n) creates two smaller calls, fib(n-1) and fib(n-2).

2

Without memoization, the same subproblem is recomputed many times. The tree grows exponentially.

3

Memoization stores each result once. Repeated calls hit the cache and the tree collapses into a linear chain.

Why it matters

Recursion is elegant but can be expensive. Memoization and dynamic programming turn exponential recursion into polynomial time — a core idea in algorithms and compiler optimization.

Complexity & details

Naive Fibonacci: O(2ⁿ) time. Memoized: O(n) time and O(n) space.

Frequently asked questions

What is memoization?+

Memoization caches the result of a function call by its arguments. When the same arguments appear again, the cached result is returned immediately.

Why does naive recursion repeat work?+

fib(5) calls fib(3) and fib(4); fib(4) calls fib(3) again. Without a cache, the same subtree is explored multiple times.