2D Dynamic Programming - aloalgo.com

2D Dynamic Programming

2D DP problems have states that depend on two variables. Common examples include grid traversal, string comparison (LCS, edit distance), and knapsack problems.

When to Use 2D DP

Use 2D DP when your state requires two changing variables:
  • Grid position (row, col)
  • Two string indices (i, j)
  • Item index + remaining capacity (i, capacity)
Rule of thumb: Number of changing variables = DP dimensions.

Example: Unique Paths

Problem: A robot starts at the top-left of an m x n grid and can only move right or down. How many unique paths exist to reach the bottom-right?
  • F - Function: dp[i][j] = number of paths to reach cell (i, j)
  • A - Arguments: row i, column j
  • S - Transition: dp[i][j] = dp[i-1][j] + dp[i][j-1]
  • T - Termination: First row and column are all 1s (only one way to reach them)

Memoization (Top-Down)

Tabulation (Bottom-Up)

2D DP Table Diagram

j = 0j = 1j = 2j = 3
i = 01111
i = 11234
i = 213610
i = 3141020

Example: Edit Distance

Problem: Given two strings, find the minimum number of operations (insert, delete, replace) to convert one to the other.
  • F - Function: dp[i][j] = min edits to convert word1[0:i] to word2[0:j]
  • A - Arguments: indices i and j
  • S - Transition:
    If chars match: dp[i][j] = dp[i-1][j-1]
    Else: dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
  • T - Termination: dp[0][j] = j, dp[i][0] = i

Example: Longest Common Subsequence

Problem: Find the length of the longest subsequence common to two strings.

Common 2D DP Patterns

Grid Problems
  • Unique paths / minimum path sum
  • State: dp[row][col]
  • Transition: Usually from dp[i-1][j] and dp[i][j-1]
String Problems
  • Edit distance, LCS, palindrome partitioning
  • State: dp[i][j] for substrings/prefixes
  • Transition: Based on character comparison at i, j
Knapsack Problems
  • 0/1 Knapsack, subset sum, partition equal subset
  • State: dp[i][capacity]
  • Transition: Include or exclude item i

Tips for 2D DP

  • Draw the table: Visualize the 2D grid and fill it out by hand for small inputs
  • Identify base cases: Usually the first row and/or column
  • Check iteration order: Make sure dependencies are computed before they're needed
  • Watch for off-by-one: String indices often need i-1 to access characters

Practice Problems

Next Steps

Ready to optimize your solutions? Continue to Space Optimization for DP to learn how to reduce memory usage in your DP solutions.
Was this helpful?
© 2026 aloalgo.com. All rights reserved.