Dynamic Programming (2-D)
Signal: two sequences to align or compare (two strings), a grid you move through, or a 1-D problem that needs a second dimension (index × remaining capacity, interval [i, j]).
Core idea: dp[i][j] depends on a few neighboring cells: typically up dp[i−1][j], left dp[i][j−1] and diagonal dp[i−1][j−1]. Fill the table in an order where those are ready (usually row by row).
The classic string DP
For strings a (length m) and b (length n), let dp[i][j] describe the prefixes a[:i] and b[:j], with an extra row and column of base cases for empty prefixes:
| Problem | If a[i−1] == b[j−1] | Else | Base |
|---|---|---|---|
| Longest Common Subsequence | dp[i−1][j−1] + 1 | max(dp[i−1][j], dp[i][j−1]) | 0 |
| Edit Distance | dp[i−1][j−1] | 1 + min(delete, insert, replace) | dp[i][0] = i, dp[0][j] = j |
Space optimization: if row i only needs row i−1, keep two rows (or one row plus a saved diagonal value): O(n) instead of O(m·n).
Interval DP
dp[i][j] = answer for the substring/subarray i..j, filled by increasing length, e.g., palindromic substrings, burst balloons, matrix-chain multiplication. Palindromic Substrings (in 1-D DP) can be solved this way, or with an O(1)-space "expand around center" trick.