cswork / templatesOpen the Line 500 list

STOP 26 · DYNAMIC PROGRAMMING

String Matching and Editing

Two-string DP over prefixes O(m × n)

Contest ratings Rating 1736–Rating 1977· median Rating 1806(3 of 10 problems rated by zerotrac)

Open the Line 500 list · stop 26 · 10 problems
Learn first
Leads to
How often asked
asked by 2 companies · in 2 reportsAmazon 1, TikTok / ByteDance 1

Warm up with this one

LC 1143Longest Common SubsequenceMedium
Stuck? Peek at the approach

Use paired-prefix states with match and skip transitions, and reconstruct a common subsequence.

Key points

  1. dp[i][j] is defined on prefixes, the first i characters of a and the first j of b, with an extra row and column for the empty string.
  2. If the last characters match, inherit dp[i-1][j-1]; otherwise replace, delete and insert map to the diagonal, upper and left cells.
  3. Longest common subsequence, distinct subsequences and wildcard matching all use this table with different transitions.

Common pitfalls

  • dp indexes are prefix lengths, so the matching character is a[i-1]; writing a[i] is off by one.
  • Forgetting row 0 and column 0: reaching the empty string takes i deletions, building from it takes j insertions.
  • In a one-row version the diagonal value is overwritten by the current row; keep it in a separate variable.

Watch it run

Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.

Interactive demo · step by step

2D DP · filling the LCS table

Longest common subsequence of "ACBD" and "ABCD"

Try your own input
∅
A
B
C
D
∅
00,0
00,1
00,2
00,3
00,4
A
01,0
·1,1
·1,2
·1,3
·1,4
C
02,0
·2,1
·2,2
·2,3
·2,4
B
03,0
·3,1
·3,2
·3,3
·3,4
D
04,0
·4,1
·4,2
·4,3
·4,4
CurrentDiscovered / computedAnswer
LCS length
—

dp[i][j] is the LCS length of the first i characters of "ACBD" and the first j of "ABCD". Row 0 and column 0 are empty strings: all 0.

InvariantRows fill left to right: when dp[i][j] is computed, the cells above, left and top-left are already final.

Template

Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 1143, with it.

Python
def edit_distance(a: str, b: str) -> int:
    m, n = len(a), len(b)
    # dp[i][j]: edits to turn a[:i] into b[:j]; row 0 and column 0 are the empty prefixes
    dp = [[0] * (n + 1) for _ in range(m + 1)]
    for i in range(m + 1):
        dp[i][0] = i
    for j in range(n + 1):
        dp[0][j] = j
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if a[i - 1] == b[j - 1]:
                dp[i][j] = dp[i - 1][j - 1]
            else:  # replace, delete from a, insert into a
                dp[i][j] = 1 + min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1])
    return dp[m][n]
C++
int editDistance(const string& a, const string& b) {
    int m = a.size(), n = b.size();
    // dp[i][j]: edits to turn a[0, i) into b[0, j); row 0 and column 0 are the empty prefixes
    vector<vector<int>> dp(m + 1, vector<int>(n + 1));
    for (int i = 0; i <= m; i++) dp[i][0] = i;
    for (int j = 0; j <= n; j++) dp[0][j] = j;
    for (int i = 1; i <= m; i++)
        for (int j = 1; j <= n; j++)
            dp[i][j] = a[i - 1] == b[j - 1]
                           ? dp[i - 1][j - 1]
                           : 1 + min({dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]});  // replace, delete, insert
    return dp[m][n];
}
Java
class Solution {
    int editDistance(String a, String b) {
        int m = a.length(), n = b.length();
        // dp[i][j]: edits to turn a[0, i) into b[0, j); row 0 and column 0 are the empty prefixes
        int[][] dp = new int[m + 1][n + 1];
        for (int i = 0; i <= m; i++) dp[i][0] = i;
        for (int j = 0; j <= n; j++) dp[0][j] = j;
        for (int i = 1; i <= m; i++)
            for (int j = 1; j <= n; j++)
                if (a.charAt(i - 1) == b.charAt(j - 1)) dp[i][j] = dp[i - 1][j - 1];
                else // replace, delete, insert
                    dp[i][j] = 1 + Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1]));
        return dp[m][n];
    }
}
Go
func editDistance(a, b string) int {
	m, n := len(a), len(b)
	// dp[i][j]: edits to turn a[:i] into b[:j]; row 0 and column 0 are the empty prefixes
	dp := make([][]int, m+1)
	for i := range dp {
		dp[i] = make([]int, n+1)
		dp[i][0] = i
	}
	for j := range dp[0] {
		dp[0][j] = j
	}
	for i := 1; i <= m; i++ {
		for j := 1; j <= n; j++ {
			if a[i-1] == b[j-1] {
				dp[i][j] = dp[i-1][j-1]
			} else { // replace, delete, insert
				dp[i][j] = 1 + min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1])
			}
		}
	}
	return dp[m][n]
}

Common variants

Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.

Splitting one string: the last word is s[j:i]O(n × L × L) time, L the longest word · O(n) space

Whether a string splits into dictionary words, or in how many ways: ok[i] says the prefix s[:i] splits, trying every start j of the last word, but only as far back as the longest word, with the dictionary in a hash set. LC 139 (Word Break); LC 2707 (Extra Characters in a String) swaps true/false for the fewest leftover characters.

Python
def word_break(s: str, words: list[str]) -> bool:
    """Can s be cut into dictionary words, each usable any number of times? (LC 139)"""
    vocab = set(words)
    longest = max(map(len, words), default=0)
    ok = [True] + [False] * len(s)  # ok[i]: the prefix s[:i] can be cut
    for i in range(1, len(s) + 1):
        for j in range(max(0, i - longest), i):  # the last word is s[j:i]
            if ok[j] and s[j:i] in vocab:
                ok[i] = True
                break
    return ok[len(s)]
C++
// Can s be cut into dictionary words, each usable any number of times? (LC 139)
bool wordBreak(const string& s, const vector<string>& words) {
    unordered_set<string> vocab(words.begin(), words.end());
    size_t longest = 0;
    for (auto& w : words) longest = max(longest, w.size());
    int n = s.size();
    vector<bool> ok(n + 1, false);  // ok[i]: the prefix s[0, i) can be cut
    ok[0] = true;
    for (int i = 1; i <= n; i++)
        for (int j = max(0, i - (int)longest); j < i && !ok[i]; j++)  // the last word is s[j, i)
            ok[i] = ok[j] && vocab.count(s.substr(j, i - j));
    return ok[n];
}
Java
class Solution {
    // Can s be cut into dictionary words, each usable any number of times? (LC 139)
    boolean wordBreak(String s, List<String> words) {
        Set<String> vocab = new HashSet<>(words);
        int longest = 0;
        for (String w : words) longest = Math.max(longest, w.length());
        int n = s.length();
        boolean[] ok = new boolean[n + 1]; // ok[i]: the prefix s[0, i) can be cut
        ok[0] = true;
        for (int i = 1; i <= n; i++)
            for (int j = Math.max(0, i - longest); j < i && !ok[i]; j++) // the last word is s[j, i)
                ok[i] = ok[j] && vocab.contains(s.substring(j, i));
        return ok[n];
    }
}
Go
// wordBreak reports whether s can be cut into dictionary words, each usable any number of times.
func wordBreak(s string, words []string) bool {
	vocab := map[string]bool{}
	longest := 0
	for _, w := range words {
		vocab[w] = true
		longest = max(longest, len(w))
	}
	ok := make([]bool, len(s)+1) // ok[i]: the prefix s[:i] can be cut
	ok[0] = true
	for i := 1; i <= len(s); i++ {
		for j := max(0, i-longest); j < i && !ok[i]; j++ { // the last word is s[j:i]
			ok[i] = ok[j] && vocab[s[j:i]]
		}
	}
	return ok[len(s)]
}
Counting subsequence matches: one row, rolled backwardsO(|s| × |t|) time · O(|t|) space

To count how often t occurs in s as a subsequence: dp[j] is the number of ways the part of s read so far forms t[:j], and reading a character c adds dp[j-1] wherever t[j-1] == c. Run j backwards, or one c would be used twice; it is the same reason the 0/1 knapsack runs backwards. LC 115 (Distinct Subsequences).

Python
def num_distinct(s: str, t: str) -> int:
    """How many times t occurs in s as a subsequence (LC 115)."""
    dp = [1] + [0] * len(t)  # dp[j]: ways the part of s read so far forms t[:j]
    for c in s:
        for j in range(len(t), 0, -1):  # backwards: this c is used at most once per match
            if t[j - 1] == c:
                dp[j] += dp[j - 1]
    return dp[len(t)]
C++
// How many times t occurs in s as a subsequence (LC 115).
unsigned long long numDistinct(const string& s, const string& t) {
    vector<unsigned long long> dp(t.size() + 1, 0);  // dp[j]: ways the part of s read so far forms t[0, j)
    dp[0] = 1;
    for (char c : s)
        for (size_t j = t.size(); j >= 1; j--)  // backwards: this c is used at most once per match
            if (t[j - 1] == c) dp[j] += dp[j - 1];
    return dp[t.size()];
}
Java
class Solution {
    // How many times t occurs in s as a subsequence (LC 115).
    long numDistinct(String s, String t) {
        long[] dp = new long[t.length() + 1]; // dp[j]: ways the part of s read so far forms t[0, j)
        dp[0] = 1;
        for (char c : s.toCharArray())
            for (int j = t.length(); j >= 1; j--) // backwards: this c is used at most once per match
                if (t.charAt(j - 1) == c) dp[j] += dp[j - 1];
        return dp[t.length()];
    }
}
Go
// numDistinct returns how many times t occurs in s as a subsequence (LC 115).
func numDistinct(s, t string) int {
	dp := make([]int, len(t)+1) // dp[j]: ways the part of s read so far forms t[:j]
	dp[0] = 1
	for i := 0; i < len(s); i++ {
		for j := len(t); j >= 1; j-- { // backwards: this character is used at most once per match
			if t[j-1] == s[i] {
				dp[j] += dp[j-1]
			}
		}
	}
	return dp[len(t)]
}

Why it works

  1. States are on prefixes: dp[i][j] concerns only the first i characters of a and the first j of b, and every edit sequence falls into one of match, replace, delete or insert by what happens to the last characters, so the transition covers every case.
  2. Inheriting dp[i−1][j−1] when the last characters match is safe: some optimal alignment pairs those two characters, so pairing them costs nothing extra.
  3. The extra row and column stand for the empty string, with dp[i][0] = i and dp[0][j] = j meaning delete everything or insert everything, which makes the boundaries uniform.

Say it in 30 seconds

When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.

中文
两个字符串的 DP,我定义 dp[i][j] 为 a 的前 i 个字符和 b 的前 j 个字符上的答案,多开一行一列代表空串。以编辑距离为例:末尾字符相同就继承左上角,不同就在替换、删除、插入对应的左上、上、左三个格子里取最小再加一。任何编辑序列都能按最后一个字符怎么处理归到这几类,所以不会漏。最长公共子序列、通配符匹配也是这张表,只是转移不同,复杂度 O(m × n)。
English
For two-string DP I let dp[i][j] be the answer for the first i characters of a and the first j of b, with an extra row and column for the empty string. For edit distance, matching last characters inherit the diagonal, and otherwise I take one plus the minimum of the diagonal, upper and left cells for replace, delete and insert. Any sequence of edits falls into one of those cases by what it does with the last characters, so nothing is missed. Longest common subsequence and wildcard matching use the same table with other transitions, in O(m × n).

Grade yourself

Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.

Key points you covered (0 of 3)
How well did you know it?

Quick quiz

4 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice

4 questions
  1. What is the edit distance (insert, delete, replace each cost 1) from "abc" to "yabd"?
  2. LCS length of strings of lengths m and n uses O(m·n) memory as a full table. If only the length is needed, how low can the memory go?
  3. m = len(a), n = len(b). What are the time and extra space?
    def lcs(a, b):
        m, n = len(a), len(b)
        dp = [[0] * (n + 1) for _ in range(m + 1)]
        for i in range(m):
            for j in range(n):
                if a[i] == b[j]:
                    dp[i + 1][j + 1] = dp[i][j] + 1
                else:
                    dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j])
        return dp[m][n]
  4. n = len(s); treat integer addition as O(1). What is the time complexity?
    from functools import lru_cache
    
    def count_decodings(s):
        @lru_cache(maxsize=None)
        def go(t):
            if not t:
                return 1
            ways = go(t[1:]) if t[0] != '0' else 0
            if len(t) >= 2 and '10' <= t[:2] <= '26':
                ways += go(t[2:])
            return ways
    
        return go(s)

Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.

Template drills

Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.

These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.

def edit_distance(a: str, b: str) -> int:
    return dp[m][n]

Practice by stage

This stop's 10 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.

Core 7

#ProblemApproachRating
1143Longest Common SubsequenceUse paired-prefix states with match and skip transitions, and reconstruct a common subsequence.
1035Uncrossed LinesInterpret uncrossed lines as a common subsequence to translate a geometric description into sequence constraints.Rating 1806
72Edit DistanceModel insertion, deletion, and replacement separately and explain precisely what both indices represent.
583Delete Operation for Two StringsDerive transitions when only deletions are allowed and cross-check the result against the LCS length formula.
97Interleaving StringDetermine the third position from the two consumed prefixes instead of making an incorrect greedy choice when characters match.
139Word BreakModel dictionary segmentation as prefix reachability, allowing word reuse and recognizing impossible partitions.
2707Extra Characters in a StringAllow characters to be skipped at a cost in the segmentation model, moving from boolean reachability to minimum loss.Rating 1736

Advanced 3

#ProblemApproachRating
712Minimum ASCII Delete Sum for Two StringsGeneralize operation counts to character weights, including cumulative deletion costs for empty prefixes.
115Distinct SubsequencesFor matching characters, distinguish using from skipping the position; count index selections rather than distinct resulting strings.
1092Shortest Common SupersequenceReconstruct an actual string in addition to finding the optimal length, handling branch choices and remaining prefixes.Rating 1977