Longest Common Subsequence Problem
Description
LeetCode Problem 1143.
Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
- For example,
"ace"is a subsequence of"abcde".
A common subsequence of two strings is a subsequence that is common to both strings.
Example 1:
Input: text1 = "abcde", text2 = "ace"
Output: 3
Explanation: The longest common subsequence is "ace" and its length is 3.
Example 2:
Input: text1 = "abc", text2 = "abc"
Output: 3
Explanation: The longest common subsequence is "abc" and its length is 3.
Example 3:
Input: text1 = "abc", text2 = "def"
Output: 0
Explanation: There is no such common subsequence, so the result is 0.
Constraints:
1 <= text1.length, text2.length <= 1000text1andtext2consist of only lowercase English characters.
Solution
Approach: Dynamic Programming on Prefixes
Let f[i][j] be the length of the longest common subsequence of the first i characters of text1 and the first j characters of text2. An empty prefix has nothing in common with anything, so f[0][j] = f[i][0] = 0. For the rest, look at the last characters text1[i-1] and text2[j-1]:
- If they are equal, it is always safe to use them as the last character of the common subsequence:
f[i][j] = f[i-1][j-1] + 1. - If they differ, at least one of them is not part of the subsequence, so drop one and keep the better result:
f[i][j] = max(f[i-1][j], f[i][j-1]).
Filling the table row by row means both smaller prefixes are always ready, and the answer is f[m][n].
Why is matching equal characters safe? Any common subsequence that does not end with this pair can be changed to end with it without getting shorter, by replacing its last character with this pair.
Complexity: O(m · n) time and space for strings of lengths m and n. Since each row only reads the row above, the table could be cut to two rows, O(n) space.
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
m, n = len(text1), len(text2)
# f[i][j]: LCS length of the prefixes text1[:i] and text2[:j].
f = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if text1[i - 1] == text2[j - 1]:
f[i][j] = f[i - 1][j - 1] + 1 # match the two last characters
else:
f[i][j] = max(f[i - 1][j], f[i][j - 1]) # drop one of them
return f[m][n]