Stage 1 · Code
Dynamic Programming & Greedy
2D Dynamic Programming
When one dimension isn't enough — grid paths, string alignment, and the classic 2D DP table where states live at the intersection of two sequences.
The Pattern
2D DP extends 1D DP to two independent dimensions. The state dp[i][j] depends on dp[i-1][j], dp[i][j-1], and sometimes dp[i-1][j-1]. The table is built row-by-row or column-by-column, and each cell answers the question: 'what's the optimal value for these prefixes?'
Think of it as solving the problem for every pair of prefixes. For grid problems, dp[i][j] is the answer for the subgrid from (0,0) to (i,j). For string problems, dp[i][j] involves the first i characters of string A and first j characters of string B.
| A | C | ||
|---|---|---|---|
0 | 0 | 0 | |
| A | 0 | 1 | 1 |
| B | 0 | 1 | 1 |
| C | 0 | 1 | 2 |
Always draw the 2D table. The recurrence tells you which neighboring cells to look at. dp[i][j] usually needs dp[i-1][j], dp[i][j-1], or dp[i-1][j-1]. Build the table systematically and the answer is dp[m][n].
Grid DP Template
LCS Pattern
The Longest Common Subsequence (LCS) is the canonical 2D string DP. dp[i][j] = LCS of first i chars of text1 and first j chars of text2. If chars match, extend the LCS by 1. If not, carry forward the best from either direction.
When to Use
- Grid path counting or minimizing cost (Unique Paths, Min Path Sum, Dungeon Game).
- Comparing two sequences (LCS, Edit Distance, Shortest Common Supersequence).
- Two independent variables that define the state (index in array A, index in array B).
- dp[i][j] depends on dp[i-1][j], dp[i][j-1], dp[i-1][j-1] — classic 2D recurrence.
- Both dimensions are bounded ≤ 1000 — 2D DP table with 10⁶ cells is fine.
Problems
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.