Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 17

Grid DP Fundamentals

This lesson is built with resources from youtube.com and algo.monster.

Introduction

Welcome to the next step in our dynamic programming journey. In the previous lesson, we mastered two fundamental 1D DP patterns: counting ways (like in Climbing Stairs) and finding an optimal value through "pick vs. not-pick" decisions (like in House Robber).

This lesson directly builds on that foundation. Our learning outcome is to solve simple 2D DP problems on grids. We will see how the logic you learned for 1D sequences elegantly extends to a two-dimensional space. The "counting" pattern evolves into the Unique Paths problem, and the "optimization" pattern evolves into the Minimum Path Sum problem.

For both problems, we will continue our rigorous practice of moving from the initial recurrence relation to a fully space-optimized bottom-up solution. This ability to reason about and progressively refine a solution is a critical signal of seniority in a coding interview.


1. Unique Paths: Counting on a 2D Grid

Let's start with the 2D equivalent of "Climbing Stairs."

Problem: You are on an m x n grid. Starting from the top-left corner (0, 0), you can only move down or right. Your goal is to reach the bottom-right corner (m-1, n-1). How many unique paths are there?

Just as reaching step n in Climbing Stairs depended on the number of ways to reach steps n-1 and n-2, reaching cell (i, j) on a grid depends on the number of ways to reach the cells from which you could have come. Since you can only move down or right, you must have arrived at (i, j) from either the cell above, (i-1, j), or the cell to the left, (i, j-1).

This gives us a simple, powerful recurrence relation:

DP on Grids Illustration
This image illustrates the core recurrence for many grid-based DP problems. The number of ways to reach the highlighted cell (6) is the sum of the ways to reach the cell above it (3) and the cell to its left (3).

To build a solid intuition for this, let's start with a short reading that formalizes this idea.

62. Unique Paths - In-Depth Explanation

This article, 'Unique Paths - In-Depth Explanation' from AlgoMonster, provides a clear, concise breakdown of the problem's intuition and the dynamic programming approach.

Please read the 'Problem Description' and 'Intuition' sections. Focus on how the movement constraints (down or right) lead directly to the additive recurrence relation. This is the foundational insight for this entire class of problems.

From Recurrence to Optimized Solution

Now that we have the recurrence, we can follow the path from a naive recursive solution to a fully optimized one. The following video provides an excellent, in-depth walkthrough of this entire process. It's one of the most comprehensive explanations available and will be our main guide for this problem.

DP 8. Grid Unique Paths | Learn Everything about DP on Grids | ALL TECHNIQUES 🔥

This video from 'take U forward' meticulously covers every stage of solving the Unique Paths problem. Watching it will solidify your understanding of the complete DP thought process.

Please watch the video from 02:48 to 32:32, and then from 32:32 to 41:00 for the space optimization. The content is broken down as follows: Recursion (02:48 - 15:32): Understand how to set up the recurrence, define the base cases (reaching the destination or going out of bounds), and analyze its exponential time complexity. Memoization (15:32 - 23:44): See how to add a DP table (dp[i][j]) to cache results and avoid re-computing overlapping subproblems, bringing the complexity down to O(m*n). Tabulation (23:44 - 32:32): Learn how to convert the top-down memoized solution into a bottom-up iterative approach, eliminating recursion stack overhead. Space Optimization (32:32 - 41:00): This is a key step. Pay close attention to the observation that to compute the current row, you only need the previous row. This allows us to reduce space from O(m*n) to O(n).

Go Implementation (Space-Optimized)

As the video demonstrated, we can optimize the space complexity of the tabulation approach to . We do this by realizing that to compute the values for the current row, we only need the values from the previous row. We can use a single 1D array to represent the previous row and update it in place to generate the current row.

Here is an idiomatic Go implementation of the space-optimized solution:

package main

// uniquePaths calculates the number of unique paths in an m x n grid.
// It uses a bottom-up DP approach with O(n) space complexity.
func uniquePaths(m int, n int) int {
    // We use a 1D DP array of size n, representing a single row.
    // Initialize it with 1s, as there is 1 way to reach any cell in the first row.
    dp := make([]int, n)
    for i := range dp {
        dp[i] = 1
    }

    // Iterate through the rest of the rows, starting from the second row (i=1).
    for i := 1; i < m; i++ {
        // Iterate through the columns, starting from the second column (j=1).
        for j := 1; j < n; j++ {
            // dp[j] currently holds the value from the previous row (i-1, j).
            // dp[j-1] holds the value from the current row but previous column (i, j-1).
            // So, the new value for dp[j] is dp[i-1][j] + dp[i][j-1].
            dp[j] = dp[j] + dp[j-1]
        }
    }

    // The final answer is the value in the last cell of the last row.
    return dp[n-1]
}

2. Minimum Path Sum: Optimization on a 2D Grid

Now, let's look at the 2D analogue of the "House Robber" optimization problem.

Problem: You are given an m x n grid filled with non-negative numbers. Find a path from the top-left to the bottom-right which minimizes the sum of all numbers along its path. You can still only move either down or right at any point in time.

Before jumping into the solution, consider a simple greedy approach: at each cell, always move to the neighbor with the smaller value. Will this work?

Greedy vs. Optimal Path in a Grid
This image perfectly illustrates why a greedy strategy fails. The locally optimal choices (Greedy Solution) lead to a globally suboptimal path sum of 112, whereas the DP-derived path (Non-Greedy Solution) finds the true minimum of 24.

This shows that we must consider the total path sum up to each point, not just the next step. This is a classic indicator for dynamic programming. The logic is nearly identical to Unique Paths, but instead of summing the possibilities, we take the minimum of the two preceding path sums.

The recurrence relation becomes:

Let's walk through this problem using a detailed article.

64. Minimum Path Sum - In-Depth Explanation

The AlgoMonster explanation for 'Minimum Path Sum' is an excellent guide. It clearly lays out the DP approach, including handling the boundary conditions (the first row and column).

Please read the 'Problem Description', 'Intuition', 'Solution Approach', and 'Example Walkthrough' sections. Focus on these key points: How the base case dp[0][0] is initialized. How the first row and first column are filled, as they only have one way to be reached. How the min() function is used in the recurrence to fill the rest of the DP table.

Go Implementation (Space-Optimized)

The space optimization for Minimum Path Sum follows the exact same logic as for Unique Paths. We only need the previous row's data to compute the current row.

Here is the space-optimized Go solution. Note how we handle the boundary conditions for the first row and first column within the loops.

package main

import "math"

// minPathSum calculates the minimum path sum in an m x n grid.
// It uses a bottom-up DP approach with O(n) space.
func minPathSum(grid [][]int) int {
    m := len(grid)
    if m == 0 {
        return 0
    }
    n := len(grid[0])
    
    // dp array stores the min path sums for the current row being processed.
    dp := make([]int, n)

    for i := 0; i < m; i++ {
        for j := 0; j < n; j++ {
            if i == 0 && j == 0 {
                // Base case: starting cell.
                dp[j] = grid[i][j]
            } else if i == 0 {
                // First row: can only come from the left.
                dp[j] = dp[j-1] + grid[i][j]
            } else if j == 0 {
                // First column: can only come from above.
                // dp[j] still holds the value from the previous row.
                dp[j] = dp[j] + grid[i][j]
            } else {
                // General case: min of coming from above or left.
                // dp[j] is the 'above' value (from previous row).
                // dp[j-1] is the 'left' value (from current row).
                minVal := math.Min(float64(dp[j]), float64(dp[j-1]))
                dp[j] = int(minVal) + grid[i][j]
            }
        }
    }

    // The result is the last element of the dp array after processing all rows.
    return dp[n-1]
}

Conclusion

In this lesson, we successfully extended the 1D DP patterns from our previous session into the 2D grid world. You've seen that what might seem like a more complex problem is often just a dimensional extension of a familiar concept.

Key Takeaways:

  • 1D Patterns in 2D:
    • Counting Ways (Climbing Stairs -> Unique Paths): The recurrence changes from summing previous sequence elements to summing values from adjacent grid cells: dp[i][j] = dp[i-1][j] + dp[i][j-1].
    • Optimization (House Robber -> Minimum Path Sum): The recurrence changes from taking the max/min of choices in a sequence to choices from adjacent grid cells: dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1]).
  • The Power of Tabulation: For grid problems, the bottom-up (tabulation) approach is often more intuitive to implement than top-down (memoization), as it mirrors the natural left-to-right, top-to-bottom traversal of the grid.
  • Space Optimization is a Constant: The pattern of reducing space from to (or ) by only storing the previous row/column is a powerful technique that applies to many grid DP problems. Being able to explain and implement this is a strong signal in an interview.

We've already gotten a head start on our next topic by implementing space optimization here. In the upcoming lesson, "Optimize space complexity in DP solutions," we will formalize this technique. We'll treat it as a general-purpose tool and review how and when to apply it across a variety of DP problems, ensuring it becomes a reliable part of your problem-solving arsenal.