2-D Dynamic Programming
1-D DP tracks one index. 2-D DP needs two, because the subproblem is pinned down by a
grid position (row, col) or by a prefix of each of two strings (i, j). You
fill a table of answers, and each cell is computed from a few neighbours already filled.
When to reach for it
Section titled “When to reach for it”- The input is a grid, and you count paths or optimize a cost moving right and down.
- The input is two strings or arrays and you compare them (common subsequence, edit cost).
- Brute force branches at every step and the same
(i, j)state repeats. - The answer for a prefix pair
(i, j)follows from the answers for smaller prefix pairs. - Sizes are small enough for an
m * ntable (typically up to about 1000 per side).
Template
Section titled “Template”# dp[i][j] = answer for the subproblem ending at (i, j)dp = [[0] * (n + 1) for _ in range(m + 1)] # extra row/col = empty-prefix base casefor i in range(1, m + 1): for j in range(1, n + 1): dp[i][j] = combine(dp[i - 1][j], # from above dp[i][j - 1], # from left dp[i - 1][j - 1]) # from diagonal (strings: both advance)return dp[m][n]The whole skill: define what dp[i][j] means in one sentence, write the recurrence,
then fix the base row and column. Each cell usually depends only on the cell above, to
the left, and diagonal. So you only need the previous row: keep one or two rows and drop
the space from O(m * n) to O(n).
Problems in this guide
Section titled “Problems in this guide”- Unique Paths — each cell is the sum of the cell above and left
- Longest Common Subsequence — match extends the diagonal, mismatch takes the better neighbour