Solving a new DP problem
35 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)When facing an unfamiliar optimization problem, start with plain recursion before designing a table. We outline the 5-step blueprint for moving from brute force to production DP.
Start with Brute Force Recursion
When you see a new dynamic programming problem in an interview, do not immediately try to draw a 2D grid. Start by writing the plain recursive brute force solution!
Ask yourself three simple questions:
- What choices can I make at each step? (Pick or skip? Move down or right? Cut here?)
- What parameters change across recursive calls? (An index i? Remaining capacity w? Left and right boundaries [i, j]?)
- What are the base cases when the problem stops?
Draw the recursion tree for a tiny test case (e.g. 3 elements). If you see the exact same subproblem being called multiple times with identical parameters, plain recursion is exponential, and dynamic programming will solve it.
From Recursion Parameters to the DP Table
The parameters that change in your recursion become the dimensions of your table: one changing parameter gives a 1D table, two give a 2D table.
Example 1 · Translating Recursion to Bottom-Up DP
public class RecursionToTabulationDemo { public static int fibMemo(int n, int[] memo) { if (n <= 1) return n; if (memo[n] != 0) return memo[n]; return memo[n] = fibMemo(n - 1, memo) + fibMemo(n - 2, memo); }
public static int fibTab(int n) { if (n <= 1) return n; int a = 0, b = 1; for (int i = 2; i <= n; i++) { int c = a + b; a = b; b = c; } return b; }
public static void main(String[] args) { System.out.println("Memo(6): " + fibMemo(6, new int[7])); System.out.println("Tab(6): " + fibTab(6)); }}Memo(6): 8 Tab(6): 8
What this code does
- Recursive state n depends on n - 1 and n - 2.
- Table orders evaluation from 2 to n, replacing recursion with loops.
- Achieves O(n) time and strictly O(1) space.
The changing parameters in your recursive function define your DP table dimensions:
- One changing parameter (like index i) -> 1D table dp[i]
- Two changing parameters (like index i and capacity w, or range [i, j]) -> 2D table dp[i][w]
- Three parameters -> 3D table (rare in interviews, but occurs in 3D knapsack or grid with steps)
Translate your recursive base cases into table initializations. Then determine the loop order: smaller subproblems must be computed before the states that read them.
Diagnosing Off-by-One and Index Offsets
The single most common bug in 2D DP is off-by-one indexing between 0-indexed strings and 1-indexed DP tables.
Example 2 · Debugging Index Offsets in Prefix DP
public class IndexOffsetDebuggingDemo { public static boolean isPrefixMatch(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 i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (s.charAt(i - 1) == p.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1]; } } } return dp[m][n]; }
public static void main(String[] args) { System.out.println("Match 'cat' and 'cat': " + isPrefixMatch("cat", "cat")); System.out.println("Match 'cat' and 'dog': " + isPrefixMatch("cat", "dog")); }}Match 'cat' and 'cat': true Match 'cat' and 'dog': false
What this code does
- DP table size (m + 1) by (n + 1) treats index 0 as empty prefix.
- Accesses characters using (i - 1) and (j - 1) safely without out-of-bounds error.
- Demonstrates clean 1-based to 0-based index alignment.
In string DP, the table is usually sized (m + 1) by (n + 1) so that index 0 represents the empty prefix. When table loops run from i = 1 to m, the character corresponding to table index i is s.charAt(i - 1), NOT s.charAt(i)! Accessing s.charAt(i) when i == m throws a StringIndexOutOfBoundsException. Always remember: table index i corresponds to prefix of length i, which ends at string index i - 1.
Space Optimization and Safe Sentinels
Once your 2D table works, inspect the recurrence to see which rows are read. If cell dp[i][j] only reads values from row i - 1, compress the table to two rolling rows or a single 1D array.
Example 3 · Safe Sentinel Overflow Prevention
import java.util.Arrays;
public class SentinelOverflowPreventionDemo { public static int minCostUnreachable(int[] costs, int target) { int INF = 1_000_000_000; int[] dp = new int[target + 1]; Arrays.fill(dp, INF); dp[0] = 0; for (int c : costs) { for (int w = c; w <= target; w++) { if (dp[w - c] != INF) { dp[w] = Math.min(dp[w], dp[w - c] + 1); } } } return dp[target] >= INF ? -1 : dp[target]; }
public static void main(String[] args) { System.out.println("Cost for target 5: " + minCostUnreachable(new int[]{2, 4}, 5)); System.out.println("Cost for target 4: " + minCostUnreachable(new int[]{2, 4}, 4)); }}Cost for target 5: -1 Cost for target 4: 1
What this code does
- Uses 1_000_000_000 instead of Integer.MAX_VALUE to avoid negative overflow when adding.
- Checks sentinel before transition to maintain numerical safety.
- Returns -1 when target is unreachable.
Beware of sentinel values: in minimum cost problems, initializing unreachable cells to Integer.MAX_VALUE can cause integer overflow! If you add 1 to Integer.MAX_VALUE, it wraps around to negative Integer.MIN_VALUE, causing Math.min to choose the incorrect negative number. Instead, use a safe large constant like 1_000_000_000 that cannot overflow when added.
Next step
Check your understanding
10 quick questions