cswork / templatesOpen the Line 500 list

STOP 23 · DYNAMIC PROGRAMMING

Grid Paths and Two-Dimensional States

Grid DP compressed to one row O(rows × cols) time · O(cols) space

Contest ratings Rating 1573–Rating 1613· median Rating 1593(2 of 8 problems rated by zerotrac)

Open the Line 500 list · stop 23 · 8 problems
Learn first
Leads to
No later stop builds on it.
How often asked
asked by 2 companies · in 2 reportsGoldman Sachs 1, Upstart 1

Warm up with this one

LC 62Unique PathsMedium
Stuck? Peek at the approach

Represent path counts with two-dimensional coordinates, handling the first row, first column, and rolling arrays.

Key points

  1. dp[r][c] depends only on the cells above and to the left, so fill row by row, left to right, in one array: before the update dp[c] is "above" and dp[c-1] is "left".
  2. The first row and column have a single source; handle them separately or use an infinity sentinel.
  3. To count paths, replace min with addition and set obstacle cells to 0.

Common pitfalls

  • Adding a cell value to an INT_MAX sentinel overflows; only ever add to finite values.
  • If moves can go in all four directions there is no fill order and DP fails; use BFS or Dijkstra.
  • After compressing to one row, save the top-left value in a variable before it is overwritten if the transition needs it.

Watch it run

Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.

Interactive demo · step by step

2D DP · filling the LCS table

Longest common subsequence of "ACBD" and "ABCD"

Try your own input
∅
A
B
C
D
∅
00,0
00,1
00,2
00,3
00,4
A
01,0
·1,1
·1,2
·1,3
·1,4
C
02,0
·2,1
·2,2
·2,3
·2,4
B
03,0
·3,1
·3,2
·3,3
·3,4
D
04,0
·4,1
·4,2
·4,3
·4,4
CurrentDiscovered / computedAnswer
LCS length
—

dp[i][j] is the LCS length of the first i characters of "ACBD" and the first j of "ABCD". Row 0 and column 0 are empty strings: all 0.

InvariantRows fill left to right: when dp[i][j] is computed, the cells above, left and top-left are already final.

Template

Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 62, with it.

Python
def min_path_sum(grid: list[list[int]]) -> int:
    """Cheapest path from top-left to bottom-right moving only right or down."""
    cols = len(grid[0])
    dp = [float("inf")] * cols  # before row r is filled, dp[c] holds row r-1
    dp[0] = 0
    for row in grid:
        for c in range(cols):
            left = dp[c - 1] if c else float("inf")
            dp[c] = min(dp[c], left) + row[c]  # from above (old dp[c]) or the left (new dp[c-1])
    return dp[-1]
C++
// Cheapest path from top-left to bottom-right moving only right or down.
int minPathSum(const vector<vector<int>>& grid) {
    int cols = grid[0].size();
    vector<int> dp(cols, INT_MAX);  // before row r is filled, dp[c] holds row r-1
    dp[0] = 0;
    for (auto& row : grid)
        for (int c = 0; c < cols; c++) {
            int best = c ? min(dp[c], dp[c - 1]) : dp[c];  // from above or from the left
            dp[c] = best + row[c];  // best is always finite here
        }
    return dp[cols - 1];
}
Java
class Solution {
    // Cheapest path from top-left to bottom-right moving only right or down.
    int minPathSum(int[][] grid) {
        int cols = grid[0].length;
        int[] dp = new int[cols]; // before row r is filled, dp[c] holds row r-1
        Arrays.fill(dp, Integer.MAX_VALUE);
        dp[0] = 0;
        for (int[] row : grid)
            for (int c = 0; c < cols; c++) {
                int best = c > 0 ? Math.min(dp[c], dp[c - 1]) : dp[c]; // from above or the left
                dp[c] = best + row[c]; // best is always finite here
            }
        return dp[cols - 1];
    }
}
Go
import "math"

// minPathSum returns the cheapest path from top-left to bottom-right moving only right or down.
func minPathSum(grid [][]int) int {
	cols := len(grid[0])
	dp := make([]int, cols) // before row r is filled, dp[c] holds row r-1
	for c := 1; c < cols; c++ {
		dp[c] = math.MaxInt
	}
	for _, row := range grid {
		for c := range row {
			best := dp[c]
			if c > 0 {
				best = min(best, dp[c-1]) // from above or from the left
			}
			dp[c] = best + row[c] // best is always finite here
		}
	}
	return dp[cols-1]
}

Common variants

Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.

Maximal square: one more than the min of up, left and up-leftO(rows × cols) time · O(cols) space

For the largest all-1 square (or the number of squares): dp is the side of the largest square whose bottom-right corner is (r, c), limited by the shortest of up, left and up-left, so it is their minimum plus one. With one row, a variable keeps the old up-left value. LC 221 (Maximal Square), LC 1277 (Count Square Submatrices with All Ones).

Python
def maximal_square(matrix: list[str]) -> int:
    """Area of the largest all-'1' square; each row is a string such as "10111" (LC 221)."""
    cols = len(matrix[0])
    dp = [0] * (cols + 1)  # dp[c + 1]: side of the largest square ending at (r, c); dp[0] stays 0
    best = 0
    for row in matrix:
        diag = 0  # the up-left neighbour: dp[c] before this row overwrote it
        for c in range(cols):
            up = dp[c + 1]
            dp[c + 1] = min(up, dp[c], diag) + 1 if row[c] == "1" else 0  # limited by up, left, up-left
            best = max(best, dp[c + 1])
            diag = up
    return best * best
C++
// Area of the largest all-'1' square; each row is a string such as "10111" (LC 221).
int maximalSquare(const vector<string>& matrix) {
    int cols = matrix[0].size(), best = 0;
    vector<int> dp(cols + 1, 0);  // dp[c + 1]: side of the largest square ending at (r, c); dp[0] stays 0
    for (const string& row : matrix) {
        int diag = 0;  // the up-left neighbour: dp[c] before this row overwrote it
        for (int c = 0; c < cols; c++) {
            int up = dp[c + 1];
            dp[c + 1] = row[c] == '1' ? min({up, dp[c], diag}) + 1 : 0;  // limited by up, left, up-left
            best = max(best, dp[c + 1]);
            diag = up;
        }
    }
    return best * best;
}
Java
class Solution {
    // Area of the largest all-'1' square; each row is a string such as "10111" (LC 221).
    int maximalSquare(String[] matrix) {
        int cols = matrix[0].length(), best = 0;
        int[] dp = new int[cols + 1]; // dp[c + 1]: side of the largest square ending at (r, c); dp[0] stays 0
        for (String row : matrix) {
            int diag = 0; // the up-left neighbour: dp[c] before this row overwrote it
            for (int c = 0; c < cols; c++) {
                int up = dp[c + 1];
                dp[c + 1] = row.charAt(c) == '1' ? Math.min(Math.min(up, dp[c]), diag) + 1 : 0; // limited by up, left, up-left
                best = Math.max(best, dp[c + 1]);
                diag = up;
            }
        }
        return best * best;
    }
}
Go
// maximalSquare returns the area of the largest all-'1' square; each row is a string (LC 221).
func maximalSquare(matrix []string) int {
	cols, best := len(matrix[0]), 0
	dp := make([]int, cols+1) // dp[c + 1]: side of the largest square ending at (r, c); dp[0] stays 0
	for _, row := range matrix {
		diag := 0 // the up-left neighbour: dp[c] before this row overwrote it
		for c := 0; c < cols; c++ {
			up := dp[c+1]
			if row[c] == '1' {
				dp[c+1] = min(up, dp[c], diag) + 1 // limited by up, left, up-left
			} else {
				dp[c+1] = 0
			}
			best = max(best, dp[c+1])
			diag = up
		}
	}
	return best * best
}
Grid DP filled backwards from the goalO(rows × cols) time · O(cols) space

When what the start needs depends on what comes later (the dungeon game requires health of at least 1 throughout), going forwards lacks information. Fill backwards from the bottom-right: the least health on entering a cell is the smaller need of right and down, minus this cell's change, but never below 1. LC 174 (Dungeon Game); LC 120 (Triangle) bottom-up also runs backwards.

Python
def min_initial_health(dungeon: list[list[int]]) -> int:
    """Least starting health to reach the bottom-right keeping health >= 1 throughout (LC 174)."""
    rows, cols = len(dungeon), len(dungeon[0])
    need = [float("inf")] * (cols + 1)  # need[c]: least health on entering (r, c)
    need[cols - 1] = 1  # a virtual cell below the goal: arrive there with at least 1
    for r in range(rows - 1, -1, -1):
        for c in range(cols - 1, -1, -1):
            nxt = min(need[c], need[c + 1])  # down (row r + 1's value) or right (already row r)
            need[c] = max(1, nxt - dungeon[r][c])
    return need[0]
C++
// Least starting health to reach the bottom-right keeping health >= 1 throughout (LC 174).
int minInitialHealth(const vector<vector<int>>& dungeon) {
    int rows = dungeon.size(), cols = dungeon[0].size();
    vector<int> need(cols + 1, INT_MAX);  // need[c]: least health on entering (r, c)
    need[cols - 1] = 1;  // a virtual cell below the goal: arrive there with at least 1
    for (int r = rows - 1; r >= 0; r--)
        for (int c = cols - 1; c >= 0; c--) {
            int next = min(need[c], need[c + 1]);  // down (row r + 1's value) or right (already row r)
            need[c] = max(1, next - dungeon[r][c]);
        }
    return need[0];
}
Java
class Solution {
    // Least starting health to reach the bottom-right keeping health >= 1 throughout (LC 174).
    int minInitialHealth(int[][] dungeon) {
        int rows = dungeon.length, cols = dungeon[0].length;
        int[] need = new int[cols + 1]; // need[c]: least health on entering (r, c)
        Arrays.fill(need, Integer.MAX_VALUE);
        need[cols - 1] = 1; // a virtual cell below the goal: arrive there with at least 1
        for (int r = rows - 1; r >= 0; r--)
            for (int c = cols - 1; c >= 0; c--) {
                int next = Math.min(need[c], need[c + 1]); // down (row r + 1's value) or right (already row r)
                need[c] = Math.max(1, next - dungeon[r][c]);
            }
        return need[0];
    }
}
Go
// minInitialHealth returns the least starting health that keeps health >= 1 to the bottom-right (LC 174).
func minInitialHealth(dungeon [][]int) int {
	rows, cols := len(dungeon), len(dungeon[0])
	need := make([]int, cols+1) // need[c]: least health on entering (r, c)
	for c := range need {
		need[c] = 1 << 60
	}
	need[cols-1] = 1 // a virtual cell below the goal: arrive there with at least 1
	for r := rows - 1; r >= 0; r-- {
		for c := cols - 1; c >= 0; c-- {
			next := min(need[c], need[c+1]) // down (row r + 1's value) or right (already row r)
			need[c] = max(1, next-dungeon[r][c])
		}
	}
	return need[0]
}

Why it works

  1. The last step into (r, c) comes from above or from the left, and the two cases are disjoint, so the minimum path sum is the cell plus min(above, left) and the path count is above plus left.
  2. Why one row suffices: filling left to right, dp[c] still holds the previous row's value (above) before its update, while dp[c−1] already holds this row's (left), exactly the two values the transition needs.

Say it in 30 seconds

When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.

中文
网格 DP 里,到达一个格子的最后一步只能从上面或左边来,所以 dp[r][c] 等于格子值加上上方和左方里更小的那个;计数题就把两者相加,障碍格设为 0。第一行和第一列只有一个来源,单独初始化或者用无穷大做哨兵。空间可以压到一行:从左往右更新时,dp[c] 更新前是上方的值,dp[c−1] 已经是左方的新值。时间 O(行 × 列),空间 O(列)。
English
In grid DP the last step into a cell comes from above or from the left, so dp[r][c] is the cell value plus the smaller of those two; for counting I add them instead and set obstacles to zero. The first row and column have only one source, so I initialise them separately or use an infinity sentinel. One row of memory is enough: filling left to right, dp[c] still holds the value above, and dp[c − 1] already holds the new value to the left. That is O(rows × cols) time and O(cols) space.

Grade yourself

Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.

Key points you covered (0 of 2)
How well did you know it?

Quick quiz

3 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice

3 questions
  1. On a 3×3 grid of cells, moving only right or down, how many paths lead from the top-left cell to the bottom-right cell?
  2. A grid DP squeezed into one row runs dp[j] = dp[j] + dp[j-1] for j from left to right. Before the assignment, what do dp[j] and dp[j-1] hold?
  3. The grid g has m rows and n columns. What are the time and extra space?
    def min_path(g):
        m, n = len(g), len(g[0])
        dp = [float('inf')] * n
        dp[0] = 0
        for i in range(m):
            for j in range(n):
                left = dp[j - 1] if j else float('inf')
                dp[j] = g[i][j] + min(dp[j], left)
        return dp[-1]

Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.

Template drills

Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.

These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.

Practice by stage

This stop's 8 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.

Foundation 1

#ProblemApproachRating
62Unique PathsRepresent path counts with two-dimensional coordinates, handling the first row, first column, and rolling arrays.

Core 6

#ProblemApproachRating
63Unique Paths IIAdd obstacles to path counting and verify blocked starts and correct resetting of rolling-array entries.
64Minimum Path SumReplace reachability with minimum cost to practice optimal substructure and boundary sentinels.
120TriangleHandle path states on rows of varying lengths and compare top-down and bottom-up space compression.
931Minimum Falling Path SumHandle three predecessors and out-of-bounds columns without mistaking newly updated states for the previous row.Rating 1573
221Maximal SquareExplain why a square's side length depends on the minimum of the left, upper, and upper-left states rather than summed areas.
1277Count Square Submatrices with All OnesReinterpret the maximum-square state as the count of squares ending at the current position to practice state reuse.Rating 1613

Advanced 1

#ProblemApproachRating
174Dungeon GameWork backward from the destination to find minimum required health and explain why forward cumulative sums alone are insufficient.