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.
2 · Watch
2-D DP in 60 seconds
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.
- Medium01
Unique Paths
Warm-up: each cell adds the ways from above and left.
Ways into a cell: the ways from above plus the ways from the left.
- Time
- O(m·n)
- Space
- O(n)
Also works with Math & Geometry.
- Medium02
Longest Common Subsequence
The one you just watched. Write it from memory.
Two strings, two indices: fill a table of answers for every pair of prefixes.
- Time
- O(m·n)
- Space
- O(m·n)