Loading algorithms…
Loading visualizer…
The canonical DP intro. Naive recursion calls fib(k) exponentially many times; a single cache collapses overlapping subproblems to O(n).
Recomputes every subproblem — exponential blowup.
Naive recursion: fib(5) starts. The recursion tree explodes because fib(k) is computed independently for every node — exponential time.
Caches every computed value — linear in n.
Memoized recursion: fibMemo(5) starts with an empty cache. Every new n will be computed once and stored.
Same Fibonacci number, two implementations. Memoization collapses the overlapping subproblems.
Fibonacci is the classic introduction to dynamic programming. Defined recursively as fib(n) = fib(n−1) + fib(n−2) with base cases fib(0) = 0 and fib(1) = 1, it looks innocent — until you compute it naively and discover the call count explodes exponentially.
Every call to fib(k) spawns two new calls. Most of those calls re-compute the same values over and over: fib(2) is computed at least 5 times in fib(7). The recursion tree has roughly 2·F(n+1) − 1 nodes — exponential.
The fix is to cache every computed value. The first time fib(k) is computed, store the answer. Every subsequent call is an O(1) lookup. The recursion tree collapses from exponential to linear: each unique k is computed once.
fib(0) up to fib(n). Same time complexity, no recursion overhead, no stack risk.Memoization trades a tiny bit of memory for a massive reduction in redundant work — the very essence of dynamic programming.