Fibonacci (Tabulation) visualization

Build F(0..n) bottom-up so each value is computed exactly once.

Naive recursion recomputes the same subproblems exponentially often. Tabulation fills dp[i] = dp[i−1] + dp[i−2] from the base cases upward — O(n) time.

Edge cases: F(0) = 0 and F(1) = 1 are returned directly; negative n is undefined for this definition.

Complexity

Time: best O(n), average O(n), worst O(n). Space: O(n). Difficulty: Beginner.

Pseudocode

procedure fib(n):
  if n < 0: error
  if n ≤ 1: return n
  dp[0] ← 0; dp[1] ← 1
  for i ← 2 to n:
    dp[i] ← dp[i−1] + dp[i−2]
  return dp[n]

More dynamic programming algorithms