DrawCode Algorithm Visualizer • Dynamic Programming • Easy

Fibonacci (Dynamic Programming)

Tags: DP, 1D, Memoization, Tabulation, Basics

1. One-Liner

Fibonacci DP stores previously computed F(i) values so each index is evaluated once, turning exponential recursion into linear work.


2. The Problem It Solves

Naive recursion for F(n) = F(n-1) + F(n-2) recomputes the same subproblems many times. You need the same mathematical sequence but with efficient time and predictable stack usage (tabulation) or top-down caching (memoization).


3. The Core Idea

Each F(k) depends only on shorter prefixes. Once F(k) is known, reuse it everywhere it is needed—like writing answers on a chalkboard instead of redoing the full derivation each time.


4. How It Works (Step-by-Step)

StepWhat Happens
1. BaseSet F(0)=0, F(1)=1 (or your problem’s definition)
2. OrderFor i from 2 to n, compute F(i)=F(i-1)+F(i-2)
3. StorageKeep an array dp[i] or two rolling variables
4. AnswerReturn dp[n]

5. Dry Run Example

n=5: dp=[0,1]i=2:1 → i=3:2 → i=4:3 → i=5:5. Result 5.


6. Key Properties

PropertyValue
Optimal substructureYes
Overlapping subproblemsYes (classic)
StateSingle index i

7. Where It Is Used

DomainUse
InterviewsCanonical DP introduction
AlgorithmsPrototype for linear DP and rolling array optimization

8. Interview Tips

Mention memo vs tabulation, O(n) time / O(1) space with two variables, and matrix exponentiation for O(log n) if asked for huge n.


9. Comparison with Other Approaches

ApproachTimeSpaceNotes
Naive recursionExponentialO(n) stackRecomputes
DP arrayO(n)O(n)Simple
Two variablesO(n)O(1)Rolling

10. Complexity

MetricValue
TimeO(n) with array; O(1) per step with rolling vars
SpaceO(n) or O(1) extra

Implementation Example (PYTHON)

def fibonacci(n: int) -> int:
    if n <= 1:
        return n
    a, b = 0, 1
    for _ in range(2, n + 1):
        a, b = b, a + b
    return b

Interactive Visualizer Workspace

Explore step-by-step interactive animations, memory state tracking, and live multi-language execution in DrawCode.

Launch Interactive Visualizer