Skip to content

Start typing to search patterns, problems and pages.

2-D DP

Picture a spreadsheet where every formula only points at the cells above and to the left. Fill it from the top-left corner and each cell becomes a small finished answer. The bottom-right cell then holds the whole answer, built without redoing a single cell.

⏱ about 15 minutesNeeds: 2D arrays, 1-D DPTime O(m·n)Space O(m·n)

2 · Watch

2-D DP in 60 seconds

“abcde” and “ace” share letters in order, but which run is longest? Listing every subsequence of “abcde” takes 32 checks, and it doubles with every letter.

3 · Now you drive

Keys:←→ stepSpace playR resetHomeEnd jump

Longest Common Subsequence

or try
Two words of 1–6 lowercase letters, separated by a space.
Make a table with a row of zeros on top and a column of zeros down the left.Step 1 of 18. “abcde” down the side, “ace” across the top. Zero row and column ready. Nothing filled yet.
Step 1 of 18
solution.ts
function lcs(a: string, b: string): number {
const dp = Array.from({ length: a.length + 1 }, () =>
new Array(b.length + 1).fill(0));
for (let i = 1; i <= a.length; i++) {
for (let j = 1; j <= b.length; j++) {
if (a[i - 1] === b[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[a.length][b.length];
}
▶ marks the line running now

4 · Your turn

0 of 2 problems solved

Start from this

// dp[i][j]: answer for first i and first j items.
const dp = Array.from({ length: m + 1 }, () =>
  new Array(n + 1).fill(0));
// Row 0 and column 0 stay as the empty cases.
for (let i = 1; i <= m; i++) {
  for (let j = 1; j <= n; j++) {
    // Each cell reads above, left and diagonal.
    dp[i][j] = combine(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
  }
}
return dp[m][n];

Easy ways to go wrong

  • Off-by-one errors between string indices and table indices.
  • Sharing one row across the table with [[0] * n] * m in Python.
  • Keeping the whole table when two rows would do.
  1. Medium01

    Unique Paths

    LeetCode 62 · Blind 75 · NeetCode 150

    Warm-up: each cell adds the ways from above and left.

  2. Medium02

    Longest Common Subsequence

    LeetCode 1143 · Blind 75 · NeetCode 150

    The one you just watched. Write it from memory.

UP NEXT · LESSON 17 OF 20GreedyTake the best move now. Never look back.