Lesson 22 · Problem-solving methods

Two-Dimensional Dynamic Programming

When a subproblem needs two numbers to name it, store the answers in a table, fill each cell from cells already done, and read the answer from one corner.

Two-Dimensional Dynamic Programming concept diagramA visual explanation of the layout and operations shown in this lesson.only two cells can reach the target, so the best route comes through one of them131151421starttargetfrom the leftfrom abovewhy it is safe to take the mina path into the target ends with onestep: rightwards, or downwards.whichever it is, the rest of thatpath must itself be cheapest to itsown cell, or swapping would be cheaper.dp[r][c] = grid[r][c] + min(dp[r−1][c], dp[r][c−1])row-major order fills both predecessors before the cell that needs them
1

When a DP Needs Two Indices

  1. Name the two indices and their ranges
  2. Write what dp[i][j] means in one sentence
  3. List every way the last step can reach (i, j)
  4. Set the border cells
  5. Fill in an order where each cell's sources come first
  6. Read the answer from the cell that matches the original question

2D dynamic programming, also called two dimensional dynamic programming, is used when one subproblem is named by two numbers instead of one. The answers go in a table dp[i][j], one cell per pair, and each cell is computed from cells already filled.

The two numbers come from the problem, not from the shape of the input. They can be a row and a column of a grid, a prefix length in each of two strings, an item count and a remaining capacity, or the two ends of an interval.

Write the meaning of a cell as a sentence first: "dp[i][j] is the cheapest cost to reach row i, column j" or "dp[i][j] is the length of the longest common subsequence of the first i letters of A and the first j letters of B". The recurrence then follows from asking how the last step into that cell can happen.

  • Grid: row and column
  • Two strings: a prefix of each
  • Knapsack: items used and capacity left
  • Intervals: left end and right end
2

Worked Example: Cheapest Path Through a Grid

Grid [[1, 3, 1], [1, 5, 1], [4, 2, 1]]: start at the top-left, end at the bottom-right, move only right or down, and minimise the sum of the cells visited. This is Minimum Path Sum; counting the paths instead is Unique Paths.

A cell can be entered only from above or from the left, so dp[r][c] = grid[r][c] + min(dp[r − 1][c], dp[r][c − 1]). The top row only has a left neighbour: 1, 4, 5. The left column only has one above: 1, 2, 6. Then dp[1][1] = 5 + min(4, 2) = 7, dp[1][2] = 1 + min(5, 7) = 6, dp[2][1] = 2 + min(7, 6) = 8, and dp[2][2] = 1 + min(6, 8) = 7.

Why taking the minimum is safe: whatever the best path into a cell is, the part before its last step must be the cheapest way to that neighbour, or swapping in the cheaper one would improve it. To get the route, walk back from the corner to the smaller neighbour each time: 7, 6, 5, 4, 1, which is right, right, down, down.

  • dp[r][c] = grid[r][c] + min(above, left)
  • Answer in the bottom-right cell: 7
  • Route recovered by walking back to the smaller neighbour
3

Fill Order Comes From the Dependencies

Draw an arrow from each cell to every cell that reads it. A correct loop order visits every cell after all the cells pointing into it. For grid paths, LCS and edit distance a cell reads above, left and the diagonal, so row by row, left to right works (and so does column by column).

Interval problems are different: dp[i][j] reads shorter intervals inside [i, j], such as dp[i + 1][j] and dp[i][j − 1]. Filling row by row from the top would read cells not done yet. Fill by interval length instead, length 1 first, or run i from the bottom up. Longest Palindromic Subsequence and Burst Balloons use this order.

Top-down recursion with a memo keyed on (i, j) avoids choosing an order at all: the recursion visits sources first by itself. It costs recursion depth and a function call per cell, so the bottom-up table is usually faster.

  • Grids and string pairs: row by row
  • Intervals: by length, shortest first
  • Memoized recursion: order is automatic, depth is the risk
Key reference

Terms, operations, and practical uses

Designing the table

  • Cell meaningOne sentence saying what dp[i][j] stores, written before any recurrence.
  • RecurrenceHow a cell is built from the cells its last step can come from.
  • BorderThe first row and column, or the empty-prefix row, set by hand because they lack some neighbours.

Filling it

  • DependencyA cell that another cell reads; it must be filled first.
  • Fill orderRow by row for grids and string pairs; by interval length for interval problems.
  • Answer cellThe cell that matches the original question, often the bottom-right corner.

Saving memory

  • Rolling rowsTwo rows swapped after each row, when a cell reads only the row above.
  • In-place rowOne array updated in a direction that keeps the old values a cell still needs.
  • Choice tableStored decisions that let the route be rebuilt when the values are compressed.
Implementation

Code in Python, C++ and Java

def min_path(grid):
    rows, cols = len(grid), len(grid[0])
    INF = float("inf")
    dp = [[INF] * cols for _ in range(rows)]
    for r in range(rows):
        for c in range(cols):
            if r == 0 and c == 0:
                dp[r][c] = grid[r][c]
                continue
            above = dp[r - 1][c] if r > 0 else INF
            left = dp[r][c - 1] if c > 0 else INF
            dp[r][c] = grid[r][c] + min(above, left)

    path, r, c = [], rows - 1, cols - 1
    while (r, c) != (0, 0):
        path.append((r, c))
        if c == 0 or (r > 0 and dp[r - 1][c] <= dp[r][c - 1]):
            r -= 1
        else:
            c -= 1
    path.append((0, 0))
    return dp[rows - 1][cols - 1], path[::-1]


cost, path = min_path([[1, 3, 1], [1, 5, 1], [4, 2, 1]])
print("Minimum path sum:", cost)
print("Path:", " ".join(f"({r},{c})" for r, c in path))
#include <algorithm>
#include <climits>
#include <iostream>
#include <utility>
#include <vector>
using namespace std;

int minPath(const vector<vector<int>>& grid, vector<pair<int, int>>& path) {
    int rows = grid.size(), cols = grid[0].size();
    const long long INF = LLONG_MAX / 2;
    vector<vector<long long>> dp(rows, vector<long long>(cols, INF));
    for (int r = 0; r < rows; r++)
        for (int c = 0; c < cols; c++) {
            if (r == 0 && c == 0) {
                dp[r][c] = grid[r][c];
                continue;
            }
            long long above = r > 0 ? dp[r - 1][c] : INF;
            long long left = c > 0 ? dp[r][c - 1] : INF;
            dp[r][c] = grid[r][c] + min(above, left);
        }

    int r = rows - 1, c = cols - 1;
    while (r != 0 || c != 0) {
        path.push_back({r, c});
        if (c == 0 || (r > 0 && dp[r - 1][c] <= dp[r][c - 1])) r--;
        else c--;
    }
    path.push_back({0, 0});
    reverse(path.begin(), path.end());
    return dp[rows - 1][cols - 1];
}

int main() {
    vector<pair<int, int>> path;
    int cost = minPath({{1, 3, 1}, {1, 5, 1}, {4, 2, 1}}, path);
    cout << "Minimum path sum: " << cost << "\nPath:";
    for (auto [r, c] : path) cout << " (" << r << "," << c << ")";
    cout << "\n";
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    static List<int[]> path = new ArrayList<>();

    static long minPath(int[][] grid) {
        int rows = grid.length, cols = grid[0].length;
        long INF = Long.MAX_VALUE / 2;
        long[][] dp = new long[rows][cols];
        for (int r = 0; r < rows; r++)
            for (int c = 0; c < cols; c++) {
                if (r == 0 && c == 0) {
                    dp[r][c] = grid[r][c];
                    continue;
                }
                long above = r > 0 ? dp[r - 1][c] : INF;
                long left = c > 0 ? dp[r][c - 1] : INF;
                dp[r][c] = grid[r][c] + Math.min(above, left);
            }

        int r = rows - 1, c = cols - 1;
        while (r != 0 || c != 0) {
            path.add(new int[]{r, c});
            if (c == 0 || (r > 0 && dp[r - 1][c] <= dp[r][c - 1])) r--;
            else c--;
        }
        path.add(new int[]{0, 0});
        Collections.reverse(path);
        return dp[rows - 1][cols - 1];
    }

    public static void main(String[] args) {
        long cost = minPath(new int[][]{{1, 3, 1}, {1, 5, 1}, {4, 2, 1}});
        StringBuilder sb = new StringBuilder("Minimum path sum: " + cost + "\nPath:");
        for (int[] p : path) sb.append(" (").append(p[0]).append(",").append(p[1]).append(")");
        System.out.println(sb);
    }
}
Watch it run

Step through it

Running on grid [[1,3,1],[1,5,1],[4,2,1]], moves right or down

dp[r][c] = cheapest path cost from (0, 0) to (r, c)cost griddp: cheapest cost to reach the cell131151421moves: right or down onlyso (r, c) can be entered only from (r − 1, c) above or (r, c − 1) to the left
Step 1

The grid and an empty table

Each cell has a cost, and a path from the top-left to the bottom-right may only step right or down. The table on the right will hold, for each cell, the cheapest total cost of any path from the start to that cell. Two numbers, the row and the column, name one subproblem, which is why the table is two-dimensional.

Output
1 / 11
4

Base Cases and the Border

Many string problems add an extra row 0 and column 0 for empty prefixes. Their values depend on the problem: 0 for LCS (nothing in common with an empty string), i and j for edit distance (delete or insert everything), true only at dp[0][0] for matching problems.

For a minimum, an unreachable cell must be infinity, not 0. A border of zeros lets min() pick a path that starts outside the grid for free. On the example grid that gives 3 instead of 7.

When the extra row is used, character i of a string sits in table row i + 1. Keep that shift in one place in the code; most off-by-one bugs in 2D DP come from mixing the two numberings.

  • Empty-prefix row and column remove edge checks
  • Unreachable = infinity for minimum, minus infinity for maximum
  • Table row i holds string index i − 1 when row 0 is the empty prefix
5

Common 2D DP Problems

Most 2D DP problems in interviews fall into a few shapes. The meaning of a cell is what tells them apart.

What dp[i][j] means in classic 2D DP problems
Problemdp[i][j] meansBuilt from
Minimum Path Sumcheapest cost to reach (i, j)above, left
Longest Common SubsequenceLCS of A[0..i) and B[0..j)diagonal + 1 if letters match, else max(above, left)
Edit Distanceedits to turn A[0..i) into B[0..j)1 + min of three neighbours, or diagonal if letters match
0/1 Knapsackbest value with first i items and capacity jrow above, same column or j − weight
Maximal Squareside of the largest square ending at (i, j)1 + min(above, left, diagonal)
Longest Palindromic Subsequenceanswer for the substring s[i..j]inner interval
  • Grid and string-pair problems read up, left and diagonal
  • Knapsack reads only the previous row
  • Interval problems read inner intervals
6

2D DP Space Optimization

If a row reads only itself and the row above, the older rows are never read again. Keep two rows and swap them, or keep one row and update it in place. For the grid, row[c] still holds the value above before it is overwritten, and row[c − 1] already holds the new value to its left: row[c] = grid[r][c] + min(row[c], row[c − 1]). The example's array goes 1 4 5, then 2 7 6, then 6 8 7.

Direction matters when a cell reads the old row's earlier columns. In 0/1 knapsack, dp[j] reads dp[j − weight] from the previous item, so the single row is updated from right to left; left to right would let one item be used twice.

The cost of saving memory is the route. A single row holds only the latest values, so the walk back from the corner is no longer possible. Keep the full table, or store each cell's choice separately, when the path itself is needed.

  • Memory O(rows × columns) down to O(columns)
  • Put the smaller dimension in the row when the problem allows
  • Knapsack in one row: iterate capacity downwards
7

Complexity and Common Mistakes

Time is the number of cells times the work per cell. Most problems do constant work per cell: O(R × C). If each cell scans a whole row or interval, as in matrix-chain or burst-balloons style problems, it becomes O(n³).

  • Writing a recurrence before saying what a cell means
  • Filling cells before the cells they read
  • Initialising the border with 0 when 0 is not a reachable value
  • Mixing string indices with table indices after adding the empty row
  • Compressing to one row in the wrong direction
  • Checking only the final answer; compare every cell of a tiny hand-made table