String DP
Compare two strings prefix by prefix in a 2D table, or one string against itself, to find subsequences, edit distances and matches.
Overview
Two strings, one table
Most string DP problems compare two strings, A of length m and B of length n. The state is a pair of prefixes: dp[i][j] is the answer for the first i characters of A and the first j characters of B. The table has (m + 1) rows and (n + 1) columns, because row 0 and column 0 stand for the empty prefix. That extra row and column are the base cases, and they are why dp[i][j] reads A[i-1] and B[j-1], not A[i] and B[j].
Every cell asks the same question: do the two last characters, A[i-1] and B[j-1], match? A match usually extends the diagonal cell, dp[i-1][j-1]. A mismatch combines the neighbors: the cell above, the cell to the left, and sometimes the diagonal too. That shape is the same for every two-string problem. Only two things change from problem to problem: what a match does and how a mismatch combines the neighbors.
- Longest common subsequence: a match gives the diagonal + 1, and a mismatch gives max(above, left). Row 0 and column 0 are 0.
- Edit distance: a match gives the diagonal, and a mismatch gives 1 + min(above, left, diagonal). Row 0 and column 0 count up as i and j.
- Distinct subsequences: a match gives above + diagonal, and a mismatch gives above. The base cases are dp[i][0] = 1 and dp[0][j] = 0.
- Wildcard matching: a match gives the diagonal, and a mismatch is false, unless the pattern character is *. Its base cases are in the section on wildcards below.
Every cell costs O(1), so all of these run in O(mn) time. Each row reads only the row above it, so two rows are enough and the space drops to O(min(m, n)) if you put the shorter string on the columns.
Sign up free to read the full topic
More Coding & DSA topics
Start free on Cariara · Coding problems · System design studio