Algorithms Playbook
PatternTime O(m · n) · Space O(m · n)9 min read

2D dynamic programming: grids and two strings

When the state needs two numbers: a position in a grid, or a position in each of two strings. Longest common subsequence, grid paths and how to read the table.

In short

If one index isn't enough to describe the subproblem, use two: dp[i][j]. Typical for grids and for problems on two strings or arrays. The table has m × n cells, each filled from its neighbours in O(1).

The idea: a table instead of a line

Longest common subsequence (LCS) of two strings: dp[i][j] is the LCS of the first i letters of s and the first j letters of t. If the last letters match, extend the diagonal (dp[i-1][j-1] + 1). If not, one of them can't be used: take the best of dropping one (max(dp[i-1][j], dp[i][j-1])).

Longest common subsequence: a 2D table
Example
Speed
0∅1B2D3C4Brows: letters of "ABCBD" · columns: letters of "BDCB"

∅

0010203040

1: A

001·2·3·4·

2: B

001·2·3·4·

3: C

001·2·3·4·

4: B

001·2·3·4·

5: D

001·2·3·4·
1def lcs(s, t):
2 m, n = len(s), len(t)
3 dp = [[0] * (n + 1) for _ in range(m + 1)]
4 for i in range(1, m + 1):
5 for j in range(1, n + 1):
6 if s[i - 1] == t[j - 1]:
7 dp[i][j] = dp[i - 1][j - 1] + 1
8 else:
9 dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
10 return dp[m][n]
dp[i][j] = length of the longest common subsequence of the first i letters of s and the first j letters of t. Row 0 and column 0 are 0: an empty string shares nothing.

Variables

sABCBD
tBDCB
Step 1/22· Cells: 0
Each cell depends only on three neighbours (above, left, diagonal). That fixed shape is what makes 2D DP mechanical once you've defined what dp[i][j] means.

The usual 2D shapes

Problemdp[i][j] meansComes from
Unique grid pathsWays to reach cell (i, j)dp[i-1][j] + dp[i][j-1]
Minimum path sumCheapest way to reach (i, j)cost + min(dp[i-1][j], dp[i][j-1])
Longest common subsequenceLCS of s[:i] and t[:j]Diagonal if match, else max(up, left)
Edit distanceEdits to turn s[:i] into t[:j]min(insert, delete, replace) + 1
0/1 knapsackBest value with first i items and capacity jTake item i or skip it

Practical tips

  • Add a row and column of padding (index 0 = empty prefix) so you never check boundaries inside the loop.
  • Fill order must guarantee that the cells you read already exist: row by row, left to right works when you only look up and left.
  • Often you only need the previous row: keep two rows (or one) and the space drops from O(m·n) to O(n).
  • To get the actual answer (not just its length), walk back from the last cell following the choice that was made.

Key takeaways

  • 01Two indices → a 2D table; each cell is built from a few neighbours.
  • 02LCS: match extends the diagonal; mismatch takes the better of up and left.
  • 03Pad with an empty row/column so the loops have no edge cases.
  • 04Keep only the previous row when you just need the final value.

Check your understanding

1 of 3

In LCS, what do you do when s[i-1] == t[j-1]?

Related topics