Practice: 2D DP
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Advanced 2D DP problems synthesize grid traversals, string matching, and multi-agent coordination. We analyze the brute-force branching before formulating optimal state tables.
Brute Force and Distinct Subsequences
Given two strings s and t, how many distinct subsequences of s equal t? With plain recursion, compare s[i] and t[j].
Example 1 · Distinct Subsequences Counting
public class DistinctSubsequencesDemo { public static int numDistinct(String s, String t) { int m = s.length(), n = t.length(); int[] dp = new int[n + 1]; dp[0] = 1; for (int i = 1; i <= m; i++) { for (int j = n; j >= 1; j--) { if (s.charAt(i - 1) == t.charAt(j - 1)) { dp[j] += dp[j - 1]; } } } return dp[n]; }
public static void main(String[] args) { System.out.println("Distinct 'rabbit' in 'rabbbit': " + numDistinct("rabbbit", "rabbit")); System.out.println("Distinct 'bag' in 'babgbag': " + numDistinct("babgbag", "bag")); }}Distinct 'rabbit' in 'rabbbit': 3 Distinct 'bag' in 'babgbag': 5
What this code does
- In 'rabbbit', three different choices of 'b' can be deleted to leave 'rabbit'.
- Reverse loop on j updates 1D array cleanly without overwriting previous states.
- Runs in O(m * n) time and O(n) space.
If characters match, we have two choices: use s[i] to match t[j] (advance both pointers: solve(i + 1, j + 1)), OR skip s[i] to find another match later (advance s only: solve(i + 1, j)). If they mismatch, we must skip s[i]. Why is plain recursion slow? At each matching character, the tree branches twice, taking O(2^n) time. With a 2D table dp[i][j], when s[i - 1] == t[j - 1], dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]. Otherwise, dp[i][j] = dp[i - 1][j], solving the problem in O(m * n) time.
Wildcard Matching Pattern Transitions
Wildcard matching allows '?' (matches any single character) and '*' (matches any sequence of characters, including empty).
Example 2 · Wildcard Matching Pattern Logic
public class WildcardMatchingDemo { public static boolean isMatch(String s, String p) { int m = s.length(), n = p.length(); boolean[][] dp = new boolean[m + 1][n + 1]; dp[0][0] = true; for (int j = 1; j <= n; j++) { if (p.charAt(j - 1) == '*') dp[0][j] = dp[0][j - 1]; } for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { char pc = p.charAt(j - 1); if (pc == s.charAt(i - 1) || pc == '?') { dp[i][j] = dp[i - 1][j - 1]; } else if (pc == '*') { dp[i][j] = dp[i][j - 1] || dp[i - 1][j]; } } } return dp[m][n]; }
public static void main(String[] args) { System.out.println("Match 'aa' with '*': " + isMatch("aa", "*")); System.out.println("Match 'cb' with '?a': " + isMatch("cb", "?a")); }}Match 'aa' with '*': true Match 'cb' with '?a': false
What this code does
- '*' matches any sequence including empty string.
- '?' matches single character; '?a' fails because 'b' does not match 'a'.
- Handles wildcards in O(m * n) time and O(m * n) space.
Brute force recursion on '' branches into two choices: treat '' as empty (solve(i, j + 1)), or treat '' as matching the current character and keeping '' available for more (solve(i + 1, j)). This recursive branching is exponential without memoization. In our 2D boolean table, when p[j - 1] == '', dp[i][j] = dp[i][j - 1] || dp[i - 1][j], filling in O(m n) time.
Dual Agent Traversals and Cherry Pickup
In Cherry Pickup, an agent walks from (0, 0) to (n - 1, n - 1) collecting cherries, and then walks back. Running two sequential passes greedily fails because the first path's choices block the optimal second path.
Example 3 · Simultaneous Two-Walker Cherry Pickup
import java.util.Arrays;
public class CherryPickupTwoWalkersDemo { public static int cherryPickup(int[][] grid) { int n = grid.length; int[][][] dp = new int[2 * n - 1][n][n]; for (int[][] mat : dp) for (int[] row : mat) Arrays.fill(row, -1); dp[0][0][0] = grid[0][0]; for (int step = 1; step < 2 * n - 1; step++) { for (int r1 = 0; r1 < n; r1++) { for (int r2 = 0; r2 < n; r2++) { int c1 = step - r1, c2 = step - r2; if (c1 < 0 || c1 >= n || c2 < 0 || c2 >= n) continue; if (grid[r1][c1] == -1 || grid[r2][c2] == -1) continue; int prev = -1; for (int dr1 = 0; dr1 <= 1; dr1++) { for (int dr2 = 0; dr2 <= 1; dr2++) { int pr1 = r1 - dr1, pr2 = r2 - dr2; if (pr1 >= 0 && pr2 >= 0 && dp[step - 1][pr1][pr2] >= 0) { prev = Math.max(prev, dp[step - 1][pr1][pr2]); } } } if (prev < 0) continue; int cherries = prev + grid[r1][c1]; if (r1 != r2) cherries += grid[r2][c2]; dp[step][r1][r2] = cherries; } } } return Math.max(0, dp[2 * n - 2][n - 1][n - 1]); }
public static void main(String[] args) { int[][] grid = { {0, 1, -1}, {1, 0, -1}, {1, 1, 1} }; System.out.println("Max cherries: " + cherryPickup(grid)); }}Max cherries: 5
What this code does
- Tracks step t = r1 + c1 = r2 + c2, reducing 4D state space to 3D.
- Adds both cherries when r1 != r2, and adds single cherry when r1 == r2.
- Finds optimal non-overlapping collection path totaling 5 cherries.
Instead, model the round trip as two agents walking simultaneously from (0, 0) to (n - 1, n - 1). Because both agents take one step per turn, after t steps, r1 + c1 = t and r2 + c2 = t. The state simplifies from 4 dimensions (r1, c1, r2, c2) to 3 dimensions (r1, c1, r2) because c2 = r1 + c1 - r2. If both agents land on the same cell, cherries are collected only once.
Stating Time and Space Rigorously in Interviews
When explaining 2D dynamic programming in interviews, follow a structured 4-point delivery:
- State: Define what dp[i][j] represents in plain words.
- Recurrence: State the transition formula and base cases clearly.
- Complexity: State time as O(states * transitions_per_state) and space as O(states).
- Space Optimization: Explain whether rolling rows or a 1D array reduces auxiliary space.
Communicating the algorithm with this clarity demonstrates engineering maturity and problem mastery.
Finish up
Mark complete & continue
Next: Interval dynamic programming