Dynamic programming · Θ(φⁿ) naive, O(n) memo or table
Fibonacci: recursion to DP
Naive recursion, memoization and a table side by side, with call counts.
The full explanation, derivation and practice are in the lesson From recursion to dynamic programming: Fibonacci three ways.
Implementation
The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.
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