Fibonacci — Dynamic Programming

Beginner
Dynamic Programming

Watch the memoization table fill cell by cell. Each value is computed exactly once using the recurrence dp[i] = dp[i-1] + dp[i-2], turning exponential recursion into linear time.

Input: n = 8

0F(8) = 2120

Max n = 20  (F(20) = 6765). Slider range 0–20.

Playback Controls

Step 1 / 170%
SpeedNormal
Space / Enter: Play·Pause
← →: Step R: Reset

Legend

Base case (dp[0], dp[1])
Source cells being read
Cell being computed
Newly filled
Previously computed
Not yet reached
Time: O(n)
Space: O(n)
Cells filled: 1 / 9
Base Case

Memoization Table — dp[0..8]

dp[0]0
dp[1]?
dp[2]?
dp[3]?
dp[4]?
dp[5]?
dp[6]?
dp[7]?
dp[8]?
dp[0] = 0
base case

Base case: dp[0] = 0 (the 0th Fibonacci number is 0)

Base Cases
dp[0] = 0dp[1] = 1
Recurrence
dp[i] = dp[i-1] + dp[i-2]
for i = 2, 3, …, n
Answer
return dp[n]
F(8) = ?

Reference implementation of Fibonacci — Dynamic Programming. Select a language tab to view and copy the code.

def fibonacci(n: int) -> int:
    if n <= 1:
        return n

    dp = [0] * (n + 1)
    dp[1] = 1

    for i in range(2, n + 1):
        dp[i] = dp[i - 1] + dp[i - 2]

    return dp[n]


for i in range(11):
    print(f"F({i}) = {fibonacci(i)}")

Python — Code Walkthrough

  1. Initialise the DP list

    dp = [0] * (n + 1)

    Python list multiplication creates n+1 zeros in one expression. dp[0] = 0 is set implicitly; dp[1] = 1 is assigned on the next line.

  2. Seed the first non-trivial base case

    dp[1] = 1

    Only this one seed assignment is needed after the zero-filled list. Everything else is derived by the loop.

  3. Fill using range(2, n + 1)

    dp[i] = dp[i - 1] + dp[i - 2]

    Python's range(2, n+1) is exclusive of n+1, so the loop visits indices 2, 3, …, n — exactly the cells that need computation.

  4. Return the result

    return dp[n]

    Python integers are arbitrary-precision, so there is no overflow. Fibonacci numbers grow exponentially, but Python handles them natively — you can safely call fibonacci(1000) and get the correct ~210-digit answer.

  5. Alternative: O(1) space with tuple swap

    a, b = 0, 1 for _ in range(n): a, b = b, a + b return a

    Python tuple unpacking makes the two-variable rolling update particularly elegant. This O(1) space form is idiomatic Python and avoids allocating the list entirely.