advertisement

Dynamic Programming Visualizer

Watch how DP tables are filled with step-by-step state transitions.

DP Table

Memoization in action

State Transition

See how values propagate

Subproblems

Break down complexity

Optimal Solution

Build from smaller solutions

Settings

About DP

Dynamic Programming solves problems by breaking them into overlapping subproblems and storing results to avoid redundant computation.

DP Table

Step 0 / 0

State Transition

Select a problem and click "Visualize DP" to see the table being filled.

When to Use DP?

  • Optimal Substructure: Optimal solution can be built from optimal subproblems
  • Overlapping Subproblems: Same subproblems are solved multiple times
  • Common examples: Fibonacci, Knapsack, LCS, Edit Distance

Key Concepts

  • Memoization: Top-down with caching
  • Tabulation: Bottom-up table filling
  • State: What defines a subproblem
  • Transition: How to compute from prior states

Examples & Anti-patterns

Good Practice

Bottom-Up Tabulation

Build up solutions from smallest subproblems - often more efficient than top-down.

// Fibonacci with tabulation
function fib(n) {
  const dp = [0, 1];
  for (let i = 2; i <= n; i++) {
    dp[i] = dp[i-1] + dp[i-2];
  }
  return dp[n];
} // O(n) time, O(n) space
Common Mistake

Recomputing Subproblems

Without memoization, you'll solve the same subproblems repeatedly.

// Without memoization - O(2^n)!
function fib(n) {
  if (n <= 1) return n;
  return fib(n-1) + fib(n-2);
}
// fib(5) recalculates fib(3) twice!

Frequently Asked Questions

Look for: 1) Optimal substructure - optimal solution uses optimal sub-solutions. 2) Overlapping subproblems - same subproblems solved multiple times. Keywords like "minimum", "maximum", "count ways", "longest" often indicate DP.

Top-down (memoization) is often easier to write and only computes needed subproblems. Bottom-up (tabulation) avoids recursion overhead and can be more space-efficient with optimization.

If dp[i] only depends on dp[i-1] and dp[i-2], you only need to store 2 values instead of the full array. This reduces O(n) space to O(1).