2-D Dynamic Programming

Recursion Family

Signal

Two strings: edit distance, LCS, grid paths

Template

Grid of subproblems indexed by (i, j).

Worked example (1)

#18

2-D Dynamic Programming

2-D DP

Given two strings, return the length of their longest common subsequence.

function longestCommonSubsequence(text1: string, text2: string): number {
  const m = text1.length, n = text2.length;
  const dp: number[][] = Array.from({ length: m + 1 }, () => new Array<number>(n + 1).fill(0));
  for (let i = 1; i <= m; i++)
    for (let j = 1; j <= n; j++)
      dp[i][j] = text1[i - 1] === text2[j - 1]
        ? dp[i - 1][j - 1] + 1
        : Math.max(dp[i - 1][j], dp[i][j - 1]);
  return dp[m][n];
}
Insight

Two sequences → a 2-D grid of subproblems; each cell looks at three neighbors.