DDSA
  • Missions
  • Atlas
  • Lens
  • Lab
←
Atlas · Dynamic programming · Topic 14 of 18

2-D Dynamic Programming

When the state needs two numbers (two positions, or position and budget), fill a grid of answers.

Spot it

Signals in the question

⌕Two strings or lists compared together (common subsequence, edit distance).

⌕Moving on a grid (unique paths, minimum path sum).

⌕A choice with a budget (knapsack: item i, capacity c).

The idea

O(m × n) time · O(m × n) space

dp[i][j] = the longest common subsequence of the first i letters of a and the first j of b. If the letters match, it's 1 + dp[i−1][j−1]; otherwise the better of dropping one letter from either side.

Template · Grid over two strings

1def lcs(a, b):2    dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]3    for i in range(1, len(a) + 1):4        for j in range(1, len(b) + 1):5            if a[i - 1] == b[j - 1]:6                dp[i][j] = 1 + dp[i - 1][j - 1]7            else:8                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])9    return dp[len(a)][len(b)]

The template, filled in for Longest Common Subsequence. The highlighted lines are the part every problem of this kind shares.

The best, free

One of each
▶︎Watch2-D Dynamic Programming, explainedNeetCode · YouTube · free↗¶ReadLongest common subsequenceWikipedia · free↗

Practice set

Loading your mission…

Common mistakes

1Off-by-one between dp indexes and string indexes: dp[i] is about the first i letters.

2Filling cells before the ones they depend on.

3Forgetting the empty-prefix row and column (all zeros).

Check yourself

Question 1 of 2

LCS of "abcde" and "ace"?