DSA · Pro · Pattern 1 of 9
2-D Dynamic Programming
20 problems.
Your progress0%
- 1st Visit
- 0/20
- 2nd Visit
- 0/20
- Revise
- 0/20
About this pattern
Two-dimensional DP stores the answer to a subproblem indexed by two parameters: most often a pair of prefixes of two strings, a cell of a grid, or a position combined with a count or a small state. Recognise it when a statement compares two sequences, asks for the cheapest path or the number of ways across a grid, or limits how many items or segments may be chosen. Define the state precisely, write the transition from smaller indices, and fill the table in an order that respects those dependencies. Typical cost is O(n * m) time; when each row depends only on the previous one, memory drops to O(m).
// dp[i][j] describes the prefixes a[0..i) and b[0..j)
int twoSequenceDp(const string& a, const string& b) {
int n = a.size(), m = b.size();
vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0)); // base row and column
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); // drop one element
if (a[i - 1] == b[j - 1])
dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + 1); // use both
}
return dp[n][m];
}