Learn / Dynamic programming

Strings DP

Two-string DP uses the state (i, j): the answer for the first i characters of one string and the first j of the other. If the current characters match, use the diagonal; otherwise take the best of dropping one character. LCS, edit distance, interleaving, wildcards and many more are this table with different rules.

How to recognise it

  • Two strings compared character by character.
  • Insertions, deletions or replacements to turn one string into another.
  • Palindromes inside one string (compare it with its reverse, or use the state (i, j) of a substring).

The table

dp[i][j] for the first i characters of a and the first j of b
if a[i-1] == b[j-1]: use dp[i-1][j-1]
else: combine dp[i-1][j], dp[i][j-1] (and dp[i-1][j-1])
ProblemMatchNo match
LCSdiagonal + 1max(up, left)
longest common substringdiagonal + 10 (a block must be unbroken)
edit distancediagonal1 + min(diagonal, up, left)
delete operationsvia LCS: m + n - 2 × LCS
distinct subsequencesways(up) + ways(diagonal)ways(up)
interleavingthe last character came from s1 or s2

One string

Palindromes use the state (i, j) for the substring s[i..j]: matching ends wrap the inside. The longest palindromic subsequence is also the LCS of s and its reverse.

Common mistakes

  • Mixing up substring (contiguous) and subsequence (not).
  • Off-by-one between string indexes and table indexes.

Problems

0 of 14 solved

Check yourself

LCS of 'abcde' and 'ace'?

Edit distance when the last characters differ takes 1 plus the minimum of?

Minimum insertions to make a palindrome equals?

In wildcard matching, what does '*' allow at cell (i, j)?