DP on Grids & Intervals

Grid path DP (unique paths, minimum path sum, maximal square) and interval DP (palindromes, burst balloons, matrix-chain) with the right fill order.

Advanced 2 min readLesson 25 of 25

Two more DP families come up constantly. Grid DP: the state is a cell and you arrive from neighbours you've already computed. Interval DP: the state is a range [i, j] built from smaller ranges inside it. The main difficulty in both is getting the fill order right.

Grid DP

When moves only go right and down, dp[r][c] depends on the cell above and the cell to the left. Filling row by row guarantees both are ready.

131151421
Minimum path sum: 1 → 3 → 1 → 1 → 1 = 7
int minPathSum(int[][] g) {
    int R = g.length, C = g[0].length;
    int[] dp = new int[C];                         // one row is enough
    for (int r = 0; r < R; r++)
        for (int c = 0; c < C; c++) {
            if (r == 0 && c == 0) dp[c] = g[0][0];
            else if (r == 0) dp[c] = dp[c - 1] + g[r][c];
            else if (c == 0) dp[c] = dp[c] + g[r][c];
            else dp[c] = Math.min(dp[c], dp[c - 1]) + g[r][c];   // above vs left
        }
    return dp[C - 1];
}

int uniquePaths(int m, int n) {
    int[] dp = new int[n];
    Arrays.fill(dp, 1);
    for (int r = 1; r < m; r++)
        for (int c = 1; c < n; c++) dp[c] += dp[c - 1];
    return dp[n - 1];
}

Maximal square

dp[r][c] = the side of the largest all-1 square whose bottom-right corner is (r, c): 1 + min(top, left, top-left) when the cell is 1. The smallest neighbour limits how far the square can grow.

int maximalSquare(char[][] m) {
    int R = m.length, C = m[0].length, best = 0;
    int[][] dp = new int[R + 1][C + 1];
    for (int r = 1; r <= R; r++)
        for (int c = 1; c <= C; c++)
            if (m[r - 1][c - 1] == '1') {
                dp[r][c] = 1 + Math.min(dp[r - 1][c - 1], Math.min(dp[r - 1][c], dp[r][c - 1]));
                best = Math.max(best, dp[r][c]);
            }
    return best * best;
}

Interval DP

dp[i][j] = the answer for the sub-range i..j. It is built from shorter ranges, so fill by increasing length (or loop i from right to left and j from left to right).

for len in 1..n:
    for i in 0..n-len:
        j = i + len - 1
        dp[i][j] = combine over split points k in [i, j] of dp[i][k], dp[k+1][j]

Longest palindromic subsequence

int longestPalindromeSubseq(String s) {
    int n = s.length();
    int[][] dp = new int[n][n];
    for (int i = n - 1; i >= 0; i--) {             // i decreasing, j increasing
        dp[i][i] = 1;
        for (int j = i + 1; j < n; j++)
            dp[i][j] = s.charAt(i) == s.charAt(j)
                ? dp[i + 1][j - 1] + 2
                : Math.max(dp[i + 1][j], dp[i][j - 1]);
    }
    return dp[0][n - 1];
}

Burst balloons: think about the last move

Choosing which balloon to burst first splits nothing cleanly, because the neighbours keep changing. Instead pick the balloon k to burst last in (i, j). Its neighbours at that moment are the fixed boundaries i and j:

dp[i][j]=max⁡i<k<j(dp[i][k]+ai⋅ak⋅aj+dp[k][j])dp[i][j] = \max_{i<k<j}\big(dp[i][k] + a_i \cdot a_k \cdot a_j + dp[k][j]\big)
int maxCoins(int[] nums) {
    int n = nums.length + 2;
    int[] a = new int[n];
    a[0] = a[n - 1] = 1;
    for (int i = 0; i < nums.length; i++) a[i + 1] = nums[i];
    int[][] dp = new int[n][n];
    for (int len = 2; len < n; len++)                 // gap between boundaries
        for (int i = 0; i + len < n; i++) {
            int j = i + len;
            for (int k = i + 1; k < j; k++)
                dp[i][j] = Math.max(dp[i][j], dp[i][k] + a[i] * a[k] * a[j] + dp[k][j]);
        }
    return dp[0][n - 1];
}

The same "choose the split / last operation" shape solves matrix-chain multiplication, minimum cost to cut a stick, minimum score triangulation and palindrome partitioning II.

TimeGrid: O(R·C). Interval: O(n²) states × O(n) splits = O(n³)SpaceO(C) for grids with a rolling row; O(n²) for intervals
Practice problems
  • Unique Pathsmedium
  • Unique Paths IIobstacles → 0medium
  • Minimum Path Summedium
  • Trianglebottom-upmedium
  • Maximal Squaremedium
  • Longest Palindromic Substringexpand around centre is simplermedium
  • Longest Palindromic Subsequencemedium
  • Palindromic Substringsmedium
  • Minimum Cost to Cut a Stickhard
  • Burst Balloonshard
  • Dungeon Gamefill from the bottom-righthard
  • Cherry Pickuptwo walkers at oncehard
Key takeaways
  • Grid DP: arrive from computed neighbours; fill row by row; a rolling row saves space.
  • Moves in all directions ⇒ graph search, not DP (unless the values give an order).
  • Interval DP: dp[i][j] from shorter ranges; fill by increasing length.
  • "Which one goes last?" turns messy interval problems into clean splits.
  • Interval DP is typically O(n³).