M32 · Dynamic Programming

From Recursion to Dynamic Programming: Fibonacci Three Ways

Naive recursive Fibonacci recomputes the same values over and over, so its call count grows exponentially. Remembering each value the first time it is computed (memoization) or computing the values in order into a table (tabulation) turns the same recurrence into a linear-time algorithm. That move, from overlapping recursion to stored subproblems, is dynamic programming.

~40 minAdvancedC# · Python · Java · C++
Curriculum: M32 Dynamic Programming · 2 of 2 lessons available

You will be able to

  • Explain why naive recursive Fibonacci makes 2·F(n+1) − 1 calls and why that is Θ(φⁿ), not just O(2ⁿ).
  • Recognise overlapping subproblems in a recursion tree and remove them with memoization.
  • Convert a memoized recursion into a bottom-up table, and reduce the table to O(1) space when only recent entries are needed.
  • Compare naive, memoized and tabulated versions by calls, time, stack depth and memory.
  • Know where Fibonacci numbers overflow 32-bit and 64-bit integers, and how each language reacts.

Helpful before this lesson

  • M11 Recursion — Base cases, the call stack, recursion trees and the first look at memoization.
  • M31 Backtracking — Choose, explore, undo: searching decision trees with pruning.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Mental model

The Fibonacci numbers are defined by a recurrence: F(0) = 0, F(1) = 1, and F(n) = F(n − 1) + F(n − 2). Translated literally into code:

fib(n):
    if n < 2: return n
    return fib(n - 1) + fib(n - 2)

This is correct, and hopelessly slow. Draw the calls for fib(5): fib(5) calls fib(4) and fib(3); fib(4) calls fib(3) again and fib(2); each fib(3) calls fib(2) again… The same questions are asked many times, and every time the whole subtree beneath them is recomputed. Those repeated questions are overlapping subproblems, and they are the signal that dynamic programming applies.

The lab shows three rows: the call stack, the stored values (empty for the naive version: it stores nothing), and a counter of how many times fib(k) has been called for each k. Run the Naive: fib(6) preset and watch fib(2) get called five times and fib(1) eight times.

How bad is the naive version?

Let C(n) be the number of calls fib(n) makes, including itself. One call plus the calls of both children:

C(0) = C(1) = 1,    C(n) = 1 + C(n − 1) + C(n − 2)

Adding 1 to both sides shows that C(n) + 1 follows the Fibonacci recurrence, which gives exactly C(n) = 2·F(n + 1) − 1: 25 calls for n = 6, 465 for n = 12, 2,692,537 for n = 30. Since F(n) = (φⁿ − ψⁿ)/√5 with φ = (1 + √5)/2 ≈ 1.618 and |ψ| < 1, F(n) is the nearest integer to φⁿ/√5, so

  • the naive version takes Θ(φⁿ) time: each increase of n multiplies the work by about 1.618;
  • O(2ⁿ) is also a correct upper bound (each call makes at most two more), but it is not tight. Claiming Θ(2ⁿ) would be wrong.

The stack depth, by contrast, is only n: one path of the recursion tree at a time. The lab caps the naive version at n = 12 so the trace stays short; the other two go to 30.

A finer point: fib(k) is called exactly F(n − k + 1) times for k ≥ 1 (and fib(0) F(n − 1) times). Read right to left, the counts row in the lab is itself the Fibonacci sequence 1, 1, 2, 3, 5, … (except for fib(0)).

Memoization: top-down dynamic programming

Keep the recursion, but remember every answer the first time it is computed:

fib(n, memo):
    if n < 2: return n
    if memo[n] is known: return memo[n]     # reuse
    memo[n] = fib(n - 1, memo) + fib(n - 2, memo)
    return memo[n]

Now fib(n − 1) computes everything below it once, and when fib(n) then asks for fib(n − 2) the answer is already stored. Every fib(k) does real work once and is otherwise answered in O(1). The exact count is 2n − 1 calls for n ≥ 1: 59 for n = 30 instead of 2.7 million. Time O(n), memory O(n) for the memo plus O(n) stack frames.

The order of the two checks matters little here, but the order of the two recursive calls matters for depth: computing fib(n − 1) first walks straight down to the base case, so the stack reaches depth n once.

Tabulation: bottom-up dynamic programming

The memoized recursion fills memo[2], memo[3], … in increasing order anyway. Do exactly that with a loop and no recursion at all:

table[0] = 0; table[1] = 1
for i in 2 .. n:
    table[i] = table[i - 1] + table[i - 2]
return table[n]

The loop order guarantees that both inputs of every entry are filled before it is computed: that is the key requirement for any bottom-up table. n − 1 additions, O(n) time, no stack. Because each entry only needs the two before it, you can keep just two variables and use O(1) memory; the teaching version keeps the full table so the lab can show it.

Strategy Calls Additions Time Extra memory
Naive recursion 2·F(n+1) − 1 F(n+1) − 1 Θ(φⁿ) O(n) stack
Memoized recursion 2n − 1 n − 1 Θ(n) O(n) memo + O(n) stack
Table 0 n − 1 Θ(n) O(n) table, or O(1) with two variables

(Counts for n ≥ 2; the costs assume O(1) additions, true for fixed-width integers.)

The general recipe

Fibonacci is the smallest example of a pattern you will use for every dynamic programming problem:

  1. State: what a subproblem is (here, one index k).
  2. Transition: how a state's answer combines smaller states' answers (F(k − 1) + F(k − 2)).
  3. Base cases: states answered directly (k = 0 and k = 1).
  4. Order: top-down with a memo, or bottom-up in an order where dependencies come first.

Memoization is often easier to write (it is the recursion plus three lines) and only computes the states that are actually needed. Tabulation avoids recursion depth limits and call overhead, and makes space optimisations visible. The two problems in the bank that use exactly this 1D shape are How many ways up the stairs? (Fibonacci in disguise) and Collect the most without taking neighbours (a max instead of a sum). The next lesson, 0/1 knapsack, uses a two-dimensional state.

Overflow: Fibonacci numbers grow fast

F(n) grows like φⁿ, so it runs out of bits quickly:

Type Last F(n) that fits Value
signed 32-bit (int) F(46) 1,836,311,903
signed 64-bit (long, int64_t) F(92) 7,540,113,804,746,346,429
unsigned 64-bit F(93) 12,200,160,415,121,876,738

The C#, Java and C++ implementations use 64-bit integers and reject n > 92 rather than return a wrong number. Without that check, C# and Java would silently wrap around to a negative value (both default to unchecked integer arithmetic), and C++ would have undefined behaviour, because signed overflow is undefined. Python's integers have unlimited precision, so the Python version has no upper bound; tabulated(1000) is a 209-digit number. For larger values in the other languages use System.Numerics.BigInteger (C#), java.math.BigInteger (Java) or a big-integer library (C++).

Language notes

  • Python: @functools.cache memoizes a function in one line. Memoized recursion still hits the recursion limit (1000 frames by default) for large n; the Python test calls memoized(n) with n a little past the limit and gets RecursionError, while tabulated(n) works.
  • C#: no built-in memoize attribute; use an array (as here) or a Dictionary<int, long>.
  • Java: avoid memoizing with HashMap.computeIfAbsent whose mapping function recurses into the same map: the documentation forbids modifying the map from the mapping function, and HashMap throws ConcurrentModificationException when it detects this (on a best-effort basis). Use an array or an explicit get/put.
  • C++: a std::vector<std::int64_t> memo initialised to −1; -1 works as "unknown" because no Fibonacci number is negative.

The teaching implementation

All four languages have Naive, Memoized and Tabulated with a Calls counter that matches the lab's Calls metric. They read one shared fixture with values and exact call counts from n = 0 to 92 (including the last values that fit in 32 and 64 bits), and compare every n up to 92 with an exact loop (BigInteger in C# and Java, unsigned 64-bit in C++, Python ints).

Common mistakes

  • Calling it "O(2ⁿ)" and stopping there. True as an upper bound; the tight bound is Θ(φⁿ).
  • A memo that is never written, or written after returning: still exponential.
  • Using 0 as the "unknown" marker when 0 is a valid answer (F(0) = 0). Here the base case catches it, but in other problems it silently disables the memo; use −1, None or a separate flag.
  • A table filled in the wrong order, reading entries that are not computed yet.
  • Ignoring overflow: F(47) in a 32-bit int is negative in C# and Java and undefined in C++.

Edge cases

  • n = 0 and n = 1 are base cases: one call, no addition, no table needed.
  • Negative n is rejected in every language.

Worked practice

1. How many calls does naive fib(10) make, and how many does the memoized version make?

Answer

Naive: 2·F(11) − 1 = 2·89 − 1 = 177. Memoized: 2·10 − 1 = 19.

2. Roughly how much longer does naive fib(40) take than naive fib(30)?

Answer

About φ¹⁰ ≈ 123 times longer: the call count goes from 2.7 million to about 331 million.

3. Rewrite the table version with O(1) extra space.

Answer

Keep the last two values: a, b = 0, 1, then repeat n times a, b = b, a + b, and return a. Each step overwrites the value that is no longer needed.

Summary

  • Naive recursion on an overlapping recurrence repeats work: Fibonacci makes 2·F(n+1) − 1 calls, Θ(φⁿ).
  • Memoization (top-down) stores each answer once: 2n − 1 calls, Θ(n).
  • Tabulation (bottom-up) fills the answers in dependency order with a loop: Θ(n), no stack, O(1) space possible.
  • Dynamic programming = state + transition + base cases + an evaluation order.
  • Fibonacci overflows 32 bits after F(46) and 64 bits after F(92); Python's integers do not overflow.

Full implementation

All three strategies in four languages, each checked against one shared fixture of values and exact call counts (n = 0 to 92, including the last values that fit in 32 and 64 bits) and compared with an exact loop for every n up to 92 (BigInteger, Python ints or unsigned 64-bit); the C#, Java and C++ versions also reject n > 92, and the Python test shows memoized recursion hitting the recursion limit while the table does not.

namespace Bekadan.Dsa.Examples.DynamicProgramming;
 
/// <summary>
/// F(n) three ways. F(0) = 0, F(1) = 1, F(n) = F(n − 1) + F(n − 2).
/// F(92) is the largest value that fits in a long, so larger n are rejected.
/// <see cref="Calls"/> counts recursive calls, as the visualizer does.
/// </summary>
public sealed class Fibonacci
{
    public const int MaxN = 92;
 
    public long Calls { get; private set; }
 
    private static void Check(int n) => ArgumentOutOfRangeException.ThrowIfGreaterThan((uint)n, (uint)MaxN, nameof(n));
 
    /// <summary>Plain recursion: 2·F(n + 1) − 1 calls, which grows like φ^n. O(n) stack.</summary>
    public long Naive(int n)
    {
        Check(n);
        return NaiveCall(n);
    }
 
    private long NaiveCall(int n)
    {
        Calls++;
        if (n < 2)
            return n;
        long a = NaiveCall(n - 1);
        long b = NaiveCall(n - 2);
        return a + b;
    }
 
    /// <summary>Top-down DP: the same recursion plus a memo. 2n − 1 calls, O(n) time and space.</summary>
    public long Memoized(int n)
    {
        Check(n);
        var memo = new long[n + 1];
        Array.Fill(memo, -1); // -1 = not computed yet
        return MemoCall(n, memo);
    }
 
    private long MemoCall(int n, long[] memo)
    {
        Calls++;
        if (n < 2)
            return n;
        if (memo[n] != -1)
            return memo[n];
        long a = MemoCall(n - 1, memo);
        long b = MemoCall(n - 2, memo);
        memo[n] = a + b;
        return memo[n];
    }
 
    /// <summary>Bottom-up DP: fill the table in increasing order. No recursion, O(n) time and space.</summary>
    public static long Tabulated(int n)
    {
        Check(n);
        if (n < 2)
            return n;
        var table = new long[n + 1];
        table[0] = 0;
        table[1] = 1;
        for (int i = 2; i <= n; i++)
            table[i] = table[i - 1] + table[i - 2];
        return table[n];
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/DynamicProgramming/Fibonacci.cs

"""F(n) three ways. F(0) = 0, F(1) = 1, F(n) = F(n - 1) + F(n - 2).
 
Python integers never overflow, so there is no upper limit on n here (C#, Java and C++
stop at F(92), the largest that fits in 64 bits). The recursive versions are limited by
the recursion limit instead; the table is not. `calls` counts recursive calls, as the
visualizer does.
"""
 
 
class Fibonacci:
    def __init__(self) -> None:
        self.calls = 0
 
    def naive(self, n: int) -> int:
        """Plain recursion: 2*F(n + 1) - 1 calls, which grows like phi**n. O(n) stack."""
        if n < 0:
            raise ValueError("n must be non-negative")
        return self._naive(n)
 
    def _naive(self, n: int) -> int:
        self.calls += 1
        if n < 2:
            return n
        a = self._naive(n - 1)
        b = self._naive(n - 2)
        return a + b
 
    def memoized(self, n: int) -> int:
        """Top-down DP: the same recursion plus a memo. 2n - 1 calls, O(n) time and space."""
        if n < 0:
            raise ValueError("n must be non-negative")
        memo: list[int | None] = [None] * (n + 1)  # None = not computed yet
        return self._memo(n, memo)
 
    def _memo(self, n: int, memo: list[int | None]) -> int:
        self.calls += 1
        if n < 2:
            return n
        known = memo[n]
        if known is not None:
            return known
        a = self._memo(n - 1, memo)
        b = self._memo(n - 2, memo)
        memo[n] = a + b
        return a + b
 
 
def tabulated(n: int) -> int:
    """Bottom-up DP: fill the table in increasing order. No recursion, O(n) time and space."""
    if n < 0:
        raise ValueError("n must be non-negative")
    if n < 2:
        return n
    table = [0] * (n + 1)
    table[1] = 1
    for i in range(2, n + 1):
        table[i] = table[i - 1] + table[i - 2]
    return table[n]

Tested on CPython 3.14.0 · examples/python/dsa_examples/fibonacci_dp.py

package dev.bekadan.dsa.dp;
 
import java.util.Arrays;
 
/**
 * F(n) three ways. F(0) = 0, F(1) = 1, F(n) = F(n − 1) + F(n − 2).
 * F(92) is the largest value that fits in a long, so larger n are rejected.
 * {@link #calls()} counts recursive calls, as the visualizer does.
 */
public final class Fibonacci {
    public static final int MAX_N = 92;
 
    private long calls;
 
    public long calls() {
        return calls;
    }
 
    private static void check(int n) {
        if (n < 0 || n > MAX_N) {
            throw new IllegalArgumentException("n must be in 0.." + MAX_N);
        }
    }
 
    /** Plain recursion: 2·F(n + 1) − 1 calls, which grows like φ^n. O(n) stack. */
    public long naive(int n) {
        check(n);
        return naiveCall(n);
    }
 
    private long naiveCall(int n) {
        calls++;
        if (n < 2) {
            return n;
        }
        long a = naiveCall(n - 1);
        long b = naiveCall(n - 2);
        return a + b;
    }
 
    /** Top-down DP: the same recursion plus a memo. 2n − 1 calls, O(n) time and space. */
    public long memoized(int n) {
        check(n);
        long[] memo = new long[n + 1];
        Arrays.fill(memo, -1); // -1 = not computed yet
        return memoCall(n, memo);
    }
 
    private long memoCall(int n, long[] memo) {
        calls++;
        if (n < 2) {
            return n;
        }
        if (memo[n] != -1) {
            return memo[n];
        }
        long a = memoCall(n - 1, memo);
        long b = memoCall(n - 2, memo);
        memo[n] = a + b;
        return memo[n];
    }
 
    /** Bottom-up DP: fill the table in increasing order. No recursion, O(n) time and space. */
    public static long tabulated(int n) {
        check(n);
        if (n < 2) {
            return n;
        }
        long[] table = new long[n + 1];
        table[0] = 0;
        table[1] = 1;
        for (int i = 2; i <= n; i++) {
            table[i] = table[i - 1] + table[i - 2];
        }
        return table[n];
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/dp/Fibonacci.java

#pragma once
 
// F(n) three ways. F(0) = 0, F(1) = 1, F(n) = F(n − 1) + F(n − 2).
// F(92) is the largest value that fits in std::int64_t (signed overflow would be
// undefined behaviour), so larger n are rejected. `calls` counts recursive calls,
// as the visualizer does.
 
#include <cstdint>
#include <stdexcept>
#include <vector>
 
namespace bekadan::dsa {
 
class Fibonacci {
public:
    static constexpr int max_n = 92;
 
    std::int64_t calls = 0;
 
    // Plain recursion: 2·F(n + 1) − 1 calls, which grows like φ^n. O(n) stack.
    std::int64_t naive(int n) {
        check(n);
        return naive_call(n);
    }
 
    // Top-down DP: the same recursion plus a memo. 2n − 1 calls, O(n) time and space.
    std::int64_t memoized(int n) {
        check(n);
        std::vector<std::int64_t> memo(static_cast<std::size_t>(n) + 1, -1);  // -1 = not computed yet
        return memo_call(n, memo);
    }
 
    // Bottom-up DP: fill the table in increasing order. No recursion, O(n) time and space.
    static std::int64_t tabulated(int n) {
        check(n);
        if (n < 2) return n;
        std::vector<std::int64_t> table(static_cast<std::size_t>(n) + 1);
        table[0] = 0;
        table[1] = 1;
        for (std::size_t i = 2; i < table.size(); ++i) {
            table[i] = table[i - 1] + table[i - 2];
        }
        return table.back();
    }
 
private:
    static void check(int n) {
        if (n < 0 || n > max_n) throw std::out_of_range("n must be in 0..92");
    }
 
    std::int64_t naive_call(int n) {
        ++calls;
        if (n < 2) return n;
        const std::int64_t a = naive_call(n - 1);
        const std::int64_t b = naive_call(n - 2);
        return a + b;
    }
 
    std::int64_t memo_call(int n, std::vector<std::int64_t>& memo) {
        ++calls;
        if (n < 2) return n;
        const auto k = static_cast<std::size_t>(n);
        if (memo[k] != -1) return memo[k];
        const std::int64_t a = memo_call(n - 1, memo);
        const std::int64_t b = memo_call(n - 2, memo);
        memo[k] = a + b;
        return memo[k];
    }
};
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/fibonacci_dp.hpp

References