2D dynamic programming: grids and two strings
When the state needs two numbers: a position in a grid, or a position in each of two strings. Longest common subsequence, grid paths and how to read the table.
In short
If one index isn't enough to describe the subproblem, use two: dp[i][j]. Typical for grids and for problems on two strings or arrays. The table has m × n cells, each filled from its neighbours in O(1).
The idea: a table instead of a line
Longest common subsequence (LCS) of two strings: dp[i][j] is the LCS of the first i letters of s and the first j letters of t. If the last letters match, extend the diagonal (dp[i-1][j-1] + 1). If not, one of them can't be used: take the best of dropping one (max(dp[i-1][j], dp[i][j-1])).
∅
1: A
2: B
3: C
4: B
5: D
1def lcs(s, t):2 m, n = len(s), len(t)3 dp = [[0] * (n + 1) for _ in range(m + 1)]4 for i in range(1, m + 1):5 for j in range(1, n + 1):6 if s[i - 1] == t[j - 1]:7 dp[i][j] = dp[i - 1][j - 1] + 18 else:9 dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])10 return dp[m][n]
Variables
The usual 2D shapes
| Problem | dp[i][j] means | Comes from |
|---|---|---|
| Unique grid paths | Ways to reach cell (i, j) | dp[i-1][j] + dp[i][j-1] |
| Minimum path sum | Cheapest way to reach (i, j) | cost + min(dp[i-1][j], dp[i][j-1]) |
| Longest common subsequence | LCS of s[:i] and t[:j] | Diagonal if match, else max(up, left) |
| Edit distance | Edits to turn s[:i] into t[:j] | min(insert, delete, replace) + 1 |
| 0/1 knapsack | Best value with first i items and capacity j | Take item i or skip it |
Practical tips
- Add a row and column of padding (index 0 = empty prefix) so you never check boundaries inside the loop.
- Fill order must guarantee that the cells you read already exist: row by row, left to right works when you only look up and left.
- Often you only need the previous row: keep two rows (or one) and the space drops from O(m·n) to O(n).
- To get the actual answer (not just its length), walk back from the last cell following the choice that was made.
Key takeaways
- 01Two indices → a 2D table; each cell is built from a few neighbours.
- 02LCS: match extends the diagonal; mismatch takes the better of up and left.
- 03Pad with an empty row/column so the loops have no edge cases.
- 04Keep only the previous row when you just need the final value.
Check your understanding
1 of 3
In LCS, what do you do when s[i-1] == t[j-1]?
Related topics
1D dynamic programming
If a recursive solution solves the same subproblem many times, store each answer once. Define dp[i] (what it means), write how it depends on smaller entries, fill it from the base case up. Time = number of states × work per state.
10 min read →Greedy
Greedy picks the locally best option at each step and never reconsiders. It's fast (often one pass, or a sort plus one pass) but only correct when a local choice is provably safe. If a small counterexample breaks it, use DP.
8 min read →