Skip to main content

LeetCode Patterns

Dynamic Programming on Grids Pattern

The Dynamic Programming on Grids pattern fills a 2D table where each cell's answer depends on a constant set of neighbors (usually up + left, or all four directions). It replaces an exponential recursion over grid paths with a single bottom-up pass, achieving O(m * n) time and O(m * n) space (or O(min(m, n)) with a rolling row).

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Complexity

Time
O(m * n)
Space
O(m * n)

When to use Dynamic Programming on Grids

  • The problem operates on a 2D matrix or implicit grid and asks for a count, min/max cost, or longest path from one corner to another.
  • Moves are restricted to a small fixed set of directions (right/down, or all four neighbors) so each cell has O(1) predecessors.
  • The answer at cell (i, j) is expressible as a recurrence on (i-1, j), (i, j-1), or adjacent cells with no cycles.
  • Memoization on a (row, col) state collapses the recursive search to O(m * n) unique subproblems.
  • You need the actual minimum-cost or maximum-value path, not just whether one exists.

Template

function gridDP(grid) {
  const m = grid.length;
  const n = grid[0].length;
  const dp = Array.from({ length: m }, () => new Array(n).fill(0));
  dp[0][0] = grid[0][0];
  for (let i = 0; i < m; i++) {
    for (let j = 0; j < n; j++) {
      if (i === 0 && j === 0) continue;
      const fromTop = i > 0 ? dp[i - 1][j] : Infinity;
      const fromLeft = j > 0 ? dp[i][j - 1] : Infinity;
      dp[i][j] = grid[i][j] + Math.min(fromTop, fromLeft);
    }
  }
  return dp[m - 1][n - 1];
}

Example LeetCode problems

#ProblemDifficultyFrequency
62Unique Pathsmediumfoundational
63Unique Paths IImediumfrequently asked
64Minimum Path Summediumfoundational
221Maximal Squaremediumcompany favorite
174Dungeon Gamehardclassic
120Trianglemediumfoundational
741Cherry Pickuphardless common

Common mistakes

  • Iterating the grid in the wrong order — forgetting to fill row 0 and column 0 as base cases before the main double loop.
  • On Dungeon Game, applying the recurrence left-to-right instead of right-to-left, which misses the constraint that health must stay positive at every step.
  • On Maximal Square, storing the side length but reporting it directly as the area instead of squaring it.
  • Allocating an O(m * n) table when a rolling 1D array of size O(n) suffices, then running out of memory on large inputs.
  • Treating an obstacle cell as a valid transition source in Unique Paths II, double-counting paths that should be blocked.

Frequently asked questions

When should I use Dynamic Programming on Grids vs BFS?

Use grid DP when the answer is a numeric optimum (count, min cost, longest side) and moves are restricted to a fixed direction set with no cycles. Use BFS when you need the shortest path in terms of number of steps on an unweighted grid, or when edges have non-trivial graph structure rather than a simple raster.

How do I reduce grid DP from O(m * n) to O(n) space?

Many grid recurrences only depend on the previous row, so you can keep a single row of length n and overwrite it in place. Be careful with cells that depend on both dp[i-1][j] and dp[i][j-1] — you may need to save one neighbor in a temp variable before overwriting.

Why is Dungeon Game solved right-to-left?

The constraint is that the knight's health must never drop to zero, so the minimum health needed at cell (i, j) depends on the minimum health at the cells he moves into next. Filling the table from the destination back to the start lets you compute the health requirement in one pass instead of a binary search.

Can grid DP handle four-direction movement?

Not directly, because four-direction movement introduces cycles, which break the topological ordering DP needs. You either need a different framework (BFS, Bellman-Ford, Dijkstra) or, in special cases like Cherry Pickup, you reduce the problem to two simultaneous one-way traversals.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill the Dynamic Programming on Grids pattern under real interview conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →