Algorithm · Dynamic programming · Θ(φⁿ) naive, O(n) memo or table
Fibonacci: recursion to dynamic programming
Naive recursion recomputes the same subproblems exponentially often; memoization or a table computes each once. The smallest example of dynamic programming.
The full derivation, edge cases and exercises are in the lesson From recursion to dynamic programming: Fibonacci three ways. Open it full width in the playground.
On this page
The idea
F(n) = F(n − 1) + F(n − 2) as written makes 2·F(n + 1) − 1 calls. Caching each answer the first time (memoization, top down) or filling a table from F(0) upward (tabulation, bottom up) brings that to O(n). Keeping only the last two values brings the space to O(1).
Steps
- Define the state (n) and the recurrence.
- Top down: recurse, but return a cached value when there is one.
- Bottom up: fill table[0], table[1], then each next entry from the previous two.
Invariants
What holds at every step; the correctness argument rests on these.
- table[i] = F(i) for every filled entry.
- Each subproblem is computed at most once.
Complexity
| Case | Time | Extra space |
|---|---|---|
| Naive recursion | Θ(φⁿ) | O(n) stack |
| Memoization | O(n) | O(n) |
| Tabulation, two variables | O(n) | O(1) |
When to use it
Use it when
- A recursion solves overlapping subproblems, and the answer to each depends only on smaller ones.
Avoid it when
- Subproblems do not overlap (plain divide and conquer is enough).
Step through it
The interactive lab for fibonacci: recursion to dynamic programming: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.
Implementation in four languages
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
Learn more
Lessons
- From recursion to dynamic programming: Fibonacci three ways· M32 Dynamic Programming
Data structures it uses
Problems, patterns and exercises
- PatternDynamic programming (1D and 2D)· O(states × transitions)
- ProblemHow many ways up the stairs?· beginner · O(n)
- ProblemCollect the most without taking neighbours· intermediate · O(n)
- Complexity exerciseNaive recursive Fibonacci· Θ(φⁿ) ≈ Θ(1.618ⁿ), within O(2ⁿ)