Return the nth Fibonacci number, where fib(0)=0, fib(1)=1, fib(n)=fib(n-1)+fib(n-2).
Naive recursion is O(2^n) — exponential and unusable beyond ~40. The iterative bottom-up version is O(n) time O(1) space; memoization caches subresults to make recursion O(n).
// Iterative — O(n) time, O(1) space
function fib(n) {
let a = 0, b = 1;
for (let i = 0; i < n; i++) [a, b] = [b, a + b];
return a;
}
// Memoized recursion
function fibMemo(n, memo = {}) {
if (n < 2) return n;
if (memo[n] !== undefined) return memo[n];
return (memo[n] = fibMemo(n - 1, memo) + fibMemo(n - 2, memo));
}Fibonacci is a stand-in for teaching memoization/dynamic programming — the same caching that speeds up expensive test-setup computations.
Naive recursive fib(50) hangs the browser tab. Why, and what is the minimal change to make it fast?