2D DP
Build 2D DP tables for longest common subsequence, edit distance, and unique paths in a grid.
- Implement LCS (longest common subsequence) with a 2D table
- Implement edit distance (Levenshtein) with insert, delete, and replace costs
- Count unique paths in a grid using 2D DP
When a problem involves two sequences or a grid, the sub-problem state needs
two dimensions: dp[i][j] encodes the answer for the first i characters of
one input and the first j of another (or row i, column j of a grid).
Three 2D DP problems
LCS: the diagonal trick
dp[i][j] compares s1[i-1] and s2[j-1]:
- Characters match: extend the LCS of the shorter prefixes:
dp[i-1][j-1] + 1. - Characters differ: the LCS is the best of "ignore the last char of s1"
or "ignore the last char of s2":
max(dp[i-1][j], dp[i][j-1]).
The table for lcs("ABCD", "ACBD") (LCS = 3):
"" A C B D
"" 0 0 0 0 0
A 0 1 1 1 1
B 0 1 1 2 2
C 0 1 2 2 2
D 0 1 2 2 3The answer is always in the bottom-right cell.
Edit distance: three operations at each cell
At each dp[i][j], three operations are available to transform s1[:i] into
s2[:j]:
- Delete
s1[i-1]: cost =dp[i-1][j] + 1 - Insert
s2[j-1]: cost =dp[i][j-1] + 1 - Replace (if characters differ): cost =
dp[i-1][j-1] + 1
The base cases initialise the first row and column: transforming an empty string into length-j costs j insertions; transforming length-i into empty costs i deletions.
Edit distance is the engine behind spell-checkers, diff tools, and DNA sequence alignment. In practice, the full table is often not needed — you only keep two rows at a time for O(min(m,n)) space.
Unique paths: simple grid DP
Every cell can only be reached from above or from the left, so the recurrence
is just dp[i][j] = dp[i-1][j] + dp[i][j-1]. The first row and first column
are all 1 because there is only one way to reach any cell along the edges
(always move in the same direction).
Where to go next
Next: lab — DP problems — three guided exercises: word break, house robber, and longest increasing subsequence.