Skip to main content

Two-Dimensional Dynamic Programming Solutions and Patterns

Comprehensive guide to 2D dynamic programming problems including grid traversal, matrix operations, and optimal substructure patterns with Java implementations.

Two-dimensional dynamic programming extends classic DP concepts to grid-based problems where decisions depend on both row and column indices, requiring careful state management and optimal substructure analysis for efficient solutions.

1. Pattern Restatement

Clarifying questions to ask the interviewer:

  1. Are we guaranteed that the input grid will have at least one cell (1x1 or larger), or should we handle empty grids?
  2. Do we need to consider whether the grid can be mutated during computation, or is it read-only?
  3. What is the expected return format — just a boolean indicating if path exists, or should we return the actual path?
  4. Are duplicate values in the grid allowed, and if so, how should we handle them in our DP state?
  5. What are the constraints on grid dimensions (e.g., maximum rows/columns), and should we optimize for time complexity to be O(mn) or better?

Restate the pattern or problem type in your own words: This is a dynamic programming pattern where we solve problems on 2D grids by building up solutions from smaller subproblems. The key idea is to use a 2D array where each cell represents the optimal solution for reaching that position from the starting point, typically by considering transitions from adjacent cells (like up/down/left/right).

Clarify the signal words and constraint shape that point to it:

  • "Grid" or "2D array" as input structure
  • "Minimum cost path", "maximum sum path", or similar optimization goals
  • Problems that involve traversing a 2D space with specific movement rules (e.g., only right or down)
  • "Count paths" or "find all valid paths" problems
  • Problems where subproblems can be built up from previous states in a grid

Note any assumptions you are making:

  • The grid is rectangular (m x n dimensions)
  • Movement is typically constrained to specific directions (e.g., right and down for grid traversal)
  • The problem can be solved by building up optimal solutions from smaller subproblems
  • Grid elements are numeric (for cost/path sum calculations)

Identify whether the pattern is best suited for static, streaming, or online scenarios if relevant: This pattern works best in static environments where the entire grid is available upfront. It's not well-suited for streaming data where new rows/columns arrive continuously, as the DP table needs to be built from the beginning. For online scenarios where we must respond to queries about subgrids, a different approach like segment trees or range queries might be more appropriate.

2. When to Use This Pattern

Signal words and constraint shapes in a problem statement that indicate this pattern:

  • "Grid" or "matrix" input with dimensions M×N
  • Problems asking for paths, counts, or optimization across 2D spaces
  • "Minimum path sum" or "maximum path sum" constraints
  • "Unique paths" from top-left to bottom-right
  • Problems involving 2D arrays where decisions at each cell depend on previous cells in two dimensions

Why this pattern fits better than the most common alternatives:

Two-dimensional dynamic programming is superior to brute force approaches because it avoids recomputing overlapping subproblems. Unlike greedy or backtracking solutions that might miss global optima or have exponential time complexity, 2D DP builds optimal solutions from smaller subproblems in a structured way. It's more efficient than 1D DP when the state space inherently requires tracking both row and column dependencies.

  • If the problem only requires tracking one dimension (like 1D path counting), use 1D DP instead
  • For problems with no overlapping subproblems (like simple recursion without memoization), use direct recursion or iteration
  • When the grid is very large and memory is constrained, consider space-optimized approaches or streaming variants

The core insight that makes this pattern work:

The key insight is that for any cell in a 2D grid, the optimal solution can be built from optimal solutions of previous cells in the same grid. Specifically, for a cell at position (i,j), its optimal value depends on either the cell above (i-1,j) or the cell to the left (i,j-1), depending on the problem constraints. This creates a clear dependency chain that allows for bottom-up construction of solutions.

This pattern works particularly well when:

  1. There are clear directional constraints (e.g., can only move right or down)
  2. The optimal solution at any point depends on previous optimal solutions in two dimensions
  3. There's a natural ordering to the grid traversal that allows for progressive building of solutions

3. Approach Evolution

Interview communication script:

"My first instinct is to think about this as a classic dynamic programming problem where we need to find the maximum sum path in a 2D grid. But let me think about what exactly we're being asked to do here - it seems like we want the maximum sum path from top-left to bottom-right.

My first instinct is to use a brute force approach where I try all possible paths, but that would be exponential time complexity O(2^(m+n)) because at each cell we have two choices - go right or down. That's definitely not acceptable.

Let me think about how to optimize this. I notice that if I maintain the invariant that dp[i][j] represents the maximum sum to reach cell (i,j), then I can build up the solution incrementally. This is a classic 2D DP pattern where each cell's optimal value depends on the optimal values of its predecessors.

I notice that if I maintain the invariant that dp[i][j] = maximum sum to reach cell (i,j) from (0,0), I can reduce it to O(mn) time by building up the solution row by row or column by column. The key insight is that for any cell (i,j), the maximum sum to reach it comes from either coming from above or from the left, whichever gives a larger sum.

The optimization is to realize that we don't need to store the entire 2D array - we can use a 1D array and update it in place, but that's only if we're just counting paths or summing with specific constraints. Since we're looking for maximum sum, we need to preserve the state properly.

Let me think about the recurrence relation: dp[i][j] = grid[i][j] + max(dp[i-1][j], dp[i][j-1]). This makes sense because to reach any cell, we must have come from either the cell above or the cell to the left."

Brute-force approach and why it is not ideal:

The brute force approach would involve exploring all possible paths from the top-left to bottom-right corner by recursively trying to go right or down at each step. For an m×n grid, this would generate 2^(m+n-2) possible paths in the worst case, resulting in exponential time complexity O(2^(m+n)) and exponential space complexity due to the recursion stack.

Improved approach and the key optimization:

The key optimization is recognizing this as a 2D dynamic programming problem where we can build the solution bottom-up. Instead of exploring all paths, we compute for each cell what is the maximum sum to reach that cell from the starting point. The recurrence relation is: dp[i][j] = grid[i][j] + max(dp[i-1][j], dp[i][j-1]).

This optimization reduces the problem from exponential time to linear time in terms of the grid size, making it O(mn) time and O(mn) space.

Final approach with step-by-step reasoning:

  1. Base case initialization: The first cell dp[0][0] = grid[0][0] is the starting point
  2. First row: For cells in first row, we can only come from left, so dp[0][j] = dp[0][j-1] + grid[0][j]
  3. First column: For cells in first column, we can only come from above, so dp[i][0] = dp[i-1][0] + grid[i][0]
  4. General case: For remaining cells, dp[i][j] = grid[i][j] + max(dp[i-1][j], dp[i][j-1])
  5. Result: The value at dp[m-1][n-1] gives us the maximum sum path

Important invariants that must hold:

  • dp[i][j] always represents the maximum sum to reach cell (i,j) from (0,0)
  • For any valid cell (i,j), we can only reach it from either (i-1,j) or (i,j-1)
  • The first row and column values are computed correctly before any internal cells
  • All previous states must be computed before computing the current state to maintain correctness

4. Data Structure Choice

For two-dimensional dynamic programming problems, the primary data structure is a 2D array or matrix to store computed states. This is essential because we need to maintain the state for each cell in the grid, which represents a subproblem.

Primary Data Structures Used

2D Array/Matrix:

  • Used to store the DP states where dp[i][j] represents the solution to the subproblem at position (i,j)
  • Time complexity: O(1) for access and update operations
  • Space complexity: O(m×n) where m and n are the dimensions of the grid

Additional Helper Structures:

  • Queue/Stack: May be used for BFS/DFS traversal in some 2D DP problems (e.g., when we need to process cells in a specific order)
  • HashMap: Useful for problems with sparse state spaces or when we want to memoize only computed states
  • PriorityQueue: When we need to process cells in order of some priority (e.g., shortest path problems)

Why Each Data Structure Is Needed

The 2D array is necessary because:

  1. It provides direct indexing to any subproblem state
  2. It maintains the dependency relationships between adjacent cells in the grid
  3. It enables efficient state transitions by accessing neighboring states

The helper structures are used when:

  1. We have specific traversal requirements (BFS/DFS)
  2. The state space is sparse and we want to avoid storing zeros
  3. We're dealing with optimization problems where ordering matters

Time and Space Impact

2D Array:

  • Time: O(1) per operation, O(m×n) total for all operations
  • Space: O(m×n) - this is the dominant factor in most cases

HashMap:

  • Time: O(log n) for access and update operations (assuming balanced tree)
  • Space: O(k) where k is the number of computed states, potentially much less than m×n

Helper Structure Usage

In some problems, we might use a queue for BFS-based DP or a stack for DFS-based DP. These help in maintaining the correct order of state processing and can simplify the implementation when we're dealing with path-based problems or when we want to process cells in a particular order rather than row-by-row/column-by-column.

For most standard 2D DP problems, a simple 2D array is sufficient and preferred due to its simplicity and optimal performance characteristics. The choice of data structures directly impacts the clarity and efficiency of the final solution, with 2D arrays being the most straightforward and performant approach for most grid-based problems.

5. Algorithm Walkthrough

Let me trace through the algorithm with a concrete example to demonstrate how it works step-by-step.

Example: grid = [[1,3,1],[1,5,1],[4,2,1]]

Step 1: Initialize the DP table with the first cell

  • dp[0][0] = 1

Step 2: Fill the first row (can only come from left)

  • dp[0][1] = dp[0][0] + grid[0][1] = 1 + 3 = 4
  • dp[0][2] = dp[0][1] + grid[0][2] = 4 + 1 = 5

Step 3: Fill the first column (can only come from above)

  • dp[1][0] = dp[0][0] + grid[1][0] = 1 + 1 = 2
  • dp[2][0] = dp[1][0] + grid[2][0] = 2 + 4 = 6

Step 4: Fill the remaining cells using the recurrence relation

  • dp[1][1] = min(dp[0][1], dp[1][0]) + grid[1][1] = min(4, 2) + 5 = 7
  • dp[1][2] = min(dp[1][1], dp[0][2]) + grid[1][2] = min(7, 5) + 1 = 6
  • dp[2][1] = min(dp[1][1], dp[2][0]) + grid[2][1] = min(7, 6) + 2 = 8
  • dp[2][2] = min(dp[2][1], dp[1][2]) + grid[2][2] = min(8, 6) + 1 = 7

Step 5: The final result is dp[2][2] = 7, which represents the minimum path sum from top-left to bottom-right.

Edge case handling:

  • When grid is empty, we return 0
  • When grid has only one element, we return that element's value
  • The algorithm naturally handles duplicate values since it always takes the minimum path

The algorithm terminates correctly because:

  1. Each cell's value depends only on previously computed cells (top and left)
  2. The recurrence relation dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j] ensures we always choose the optimal path
  3. The base cases (first row and column) are correctly handled to avoid index out of bounds errors

6. Java Solution

public class TwoDimensionalDP {
    
    /**
     * Solves the classic 2D grid path problem with obstacles.
     * Returns number of unique paths from top-left to bottom-right,
     * avoiding obstacles marked as 1.
     */
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        if (obstacleGrid == null || obstacleGrid.length == 0 || 
            obstacleGrid[0].length == 0) {
            return 0;
        }
        
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;
        
        // Handle edge case where start or end is blocked
        if (obstacleGrid[0][0] == 1 || obstacleGrid[m-1][n-1] == 1) {
            return 0;
        }
        
        // dp[i][j] represents number of paths to reach cell (i,j)
        int[][] dp = new int[m][n];
        
        // Initialize first cell
        dp[0][0] = 1;
        
        // Fill first row - can only come from left
        for (int j = 1; j < n; j++) {
            dp[0][j] = obstacleGrid[0][j] == 0 ? dp[0][j-1] : 0;
        }
        
        // Fill first column - can only come from above
        for (int i = 1; i < m; i++) {
            dp[i][0] = obstacleGrid[i][0] == 0 ? dp[i-1][0] : 0;
        }
        
        // Fill the rest of the dp table
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (obstacleGrid[i][j] == 0) {
                    dp[i][j] = dp[i-1][j] + dp[i][j-1];
                } else {
                    dp[i][j] = 0; // Obstacle blocks all paths to this cell
                }
            }
        }
        
        return dp[m-1][n-1];
    }
    
    /**
     * Space-optimized version using only one row
     */
    public int uniquePathsWithObstaclesOptimized(int[][] obstacleGrid) {
        if (obstacleGrid == null || obstacleGrid.length == 0 || 
            obstacleGrid[0].length == 0) {
            return 0;
        }
        
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;
        
        if (obstacleGrid[0][0] == 1 || obstacleGrid[m-1][n-1] == 1) {
            return 0;
        }
        
        // Use only one row to save space
        int[] dp = new int[n];
        dp[0] = 1;
        
        // Process each row
        for (int i = 0; i < m; i++) {
            // Handle first column
            dp[0] = obstacleGrid[i][0] == 0 ? dp[0] : 0;
            
            // Process remaining columns
            for (int j = 1; j < n; j++) {
                if (obstacleGrid[i][j] == 0) {
                    dp[j] = dp[j] + dp[j-1];
                } else {
                    dp[j] = 0;
                }
            }
        }
        
        return dp[n-1];
    }
}

The solution implements the classic 2D dynamic programming approach for path counting problems. It uses a bottom-up DP table where each cell represents the number of ways to reach that position from the start. The space-optimized version reduces memory usage by maintaining only one row at a time, which is particularly useful for large grids where memory constraints are a concern.

7. Complexity Analysis

Time Complexity: O(m × n) where m is the number of rows and n is the number of columns in the grid.

The solution uses a nested loop structure that iterates through each cell of the 2D grid exactly once. For each cell, we perform constant-time operations to compute the minimum path sum by taking the minimum of the cell above and the cell to the left. Since we process each of the m × n cells exactly once, the overall time complexity is linear in the total number of cells.

Space Complexity: O(1) for the optimized in-place solution, or O(m × n) for the standard 2D DP table approach.

The in-place solution modifies the input grid directly, using only the existing space for computation. No additional data structures are created beyond a few integer variables for tracking indices and temporary values.

If we were to use a separate DP table (which is not required for this specific problem), the space complexity would be O(m × n) as we'd need to store the computed values for each cell in a new matrix of the same dimensions.

Why these bounds are correct:

  • The time complexity is tight because we must examine every cell at least once to determine the optimal path, and our algorithm does exactly that.
  • The space complexity is optimal for the in-place variant since we're not using any additional space proportional to the input size beyond a constant number of variables.
  • The solution is optimal because it achieves the best possible time complexity for this problem (we must process each cell at least once) and space complexity (we can compute the result in-place without requiring additional storage proportional to input size).

This is near-optimal for the constraints given, as there's no way to avoid processing each cell at least once to compute a path sum from top-left to bottom-right in a grid with fixed movement rules.

8. Edge Cases & Pitfalls

Empty and Minimal Inputs

  • Empty grid: An empty 2D array (0×0) should return 0 or handle gracefully
  • Single cell grid: A 1×1 grid should work correctly, with base case handling
  • Single row/column: Grids with only one row or column require careful boundary condition handling

Duplicate Values and Repeated States

  • Identical values: When all cells have the same value, the algorithm should still compute the correct path
  • Zero values: Grids containing zeros can create unexpected paths or affect dynamic programming state transitions

Boundary Conditions

  • Out of bounds: When moving to adjacent cells, ensure indices don't go negative or exceed grid dimensions
  • Corner cases: Top-left and bottom-right corners must be handled correctly in path calculations
  • Row/column size mismatches: Grids with different row lengths (jagged arrays) should be handled gracefully

Common Implementation Mistakes

  • Incorrect base case initialization: For grid paths, dp[0][0] = grid[0][0] but not setting up the first row/column properly can cause wrong results
  • Mutation of input: Modifying the original grid instead of using a separate DP table can lead to incorrect state tracking
  • Off-by-one errors: When iterating through rows and columns, particularly in the initialization loop for first row/column
  • Missing boundary checks: Not validating that row >= 0 && col >= 0 when computing path sums can cause runtime exceptions
// Example of incorrect initialization that causes wrong results:
// dp[0][0] = grid[0][0]; // Correct
// But if we don't properly handle first row/column:
// dp[0][j] = dp[0][j-1] + grid[0][j]; // Should be: dp[0][j] = dp[0][j-1] + grid[0][j]
// But if j=0, we get dp[0][0] = dp[0][-1] + grid[0][0], which is wrong

9. Alternative Approaches

There are several alternative approaches to solving two-dimensional DP problems, each with different trade-offs:

1. Space-Optimized 1D DP: For problems where we only need the previous row/column, we can reduce space complexity from O(m×n) to O(n) or O(m). This works when the recurrence relation only depends on the immediately previous state. However, this approach requires careful indexing and can make code harder to read.

2. Memoization with Recursion: Instead of bottom-up DP, we can use top-down recursion with memoization. This is more intuitive for some problems but has O(m×n) space overhead from the call stack and memoization table. It's particularly useful when the state transitions are complex or sparse.

3. Matrix Exponentiation: For linear recurrence relations in 2D grids (like path counting with specific moves), we can use matrix exponentiation to achieve O(log n) time complexity. This is overkill for most problems but useful when the same pattern repeats across large grids.

4. BFS/DFS with State Tracking: For grid traversal problems, we can sometimes solve using graph search algorithms instead of DP. This is more intuitive but typically has higher time complexity and doesn't leverage the optimal substructure property that makes DP efficient.

The chosen solution is preferred because it provides clean, readable code with optimal time complexity O(m×n) and space complexity O(m×n), making it suitable for real-time systems where both performance and maintainability matter. The direct DP approach is more straightforward to understand and debug than alternatives like matrix exponentiation or complex memoization patterns.

10. Test Cases

public class TestCases {
    public static void main(String[] args) {
        // Test Case 1: Basic example from problem description
        int[][] matrix1 = {
            {1, 3, 1},
            {1, 5, 1},
            {4, 2, 1}
        };
        // Expected: 7 (path: 1→1→1→1)
        
        // Test Case 2: Single row
        int[][] matrix2 = {{1, 2, 3}};
        // Expected: 6 (path: 1→2→3)
        
        // Test Case 3: Single column
        int[][] matrix3 = {{1}, {2}, {3}};
        // Expected: 6 (path: 1→2→3)
        
        // Test Case 4: All negative numbers
        int[][] matrix4 = {{-1, -2}, {-3, -4}};
        // Expected: -6 (path: -1→-2→-4)
        
        // Test Case 5: Mixed positive and negative
        int[][] matrix5 = {{1, -3, 2}, {-1, 5, -1}, {1, -2, 1}};
        // Expected: -1 (path: 1→-3→2→-1)
        
        // Test Case 6: Empty matrix (edge case)
        int[][] matrix6 = {};
        // Expected: 0 or handle appropriately
        
        // Test Case 7: Matrix with zeros
        int[][] matrix7 = {{1, 0, 1}, {0, 1, 0}, {1, 0, 1}};
        // Expected: 3 (path: 1→0→1→0→1)
    }
}

Sample test cases include:

  • Basic valid matrix with positive integers
  • Edge case of single row or column matrices
  • Negative number scenarios to test path selection logic
  • Empty matrix handling
  • Zero-value elements that could affect optimal path calculation

The test cases cover typical scenarios and edge conditions to validate correctness across different input configurations.

11. Final Summary

This solution efficiently solves the two-dimensional dynamic programming problem by leveraging the optimal substructure property where each cell's value depends only on previously computed neighboring cells. The approach uses a 2D array to store intermediate results, avoiding redundant computations that would occur with a naive recursive solution. The key insight is recognizing that we can compute values in a specific order (typically row-by-row or column-by-column) to ensure all dependencies are resolved before they're needed. This leads to an optimal O(m×n) time and space complexity solution where m and n are the dimensions of the input grid, making it well-suited for large inputs within FAANG constraints. The solution's elegance lies in its ability to transform a complex multi-dimensional decision problem into a straightforward iterative computation that builds upon previously solved subproblems.

Was this article helpful?

Topics in this article

More from DSA Patterns

  • DSA Patterns

    Dynamic Programming Knapsack Problem Solutions

    Comprehensive Java implementation of classic knapsack problems including 0/1, unbounded, and bounded variants with optimal time and space complexity analysis.

  • DSA Problems

    Rotting Oranges Java Solution with BFS

    Complete Java implementation of the rotting oranges problem using breadth-first search to find minimum time for all oranges to rot.

  • DSA Patterns

    Trapping Rain Water Algorithm Solution

    Complete Java implementation of the trapping rain water problem with multiple approaches including two-pointer and dynamic programming techniques.

Stay in the Loop

Get curated DSA patterns, coding problems, frontend and backend LLD/HLD, and AI/ML System Design insights delivered straight to your inbox. No spam, just focused interview and engineering content.