1143. Longest Common Subsequence
Asked at 19Microsoft46Apple46Google39Amazon37Meta35Bloomberg30Visa39Optum68Arista Networks60ByteDance59ServiceNow55Salesforce55Morgan Stanley54DoorDash45Walmart Labs43Cisco37TikTok35Infosys30tcs27
Problem
Return the length of the longest common subsequence of text1 and text2 (characters in order, not necessarily adjacent), or 0 if there is none.
Example: text1 = "abcde", text2 = "ace" → 3
Constraints: lengths ≤ 1000.
Characters match → extend the diagonal: dp[i][j] = dp[i−1][j−1] + 1; else max(dp[i−1][j], dp[i][j−1]). See the table in the topic intro.
Complexity: O(m·n) time, O(n) space.
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
n = len(text2)
dp = [0] * (n + 1)
for a in text1:
diag = 0
for j in range(1, n + 1):
up = dp[j]
dp[j] = diag + 1 if a == text2[j - 1] else max(dp[j], dp[j - 1])
diag = up
return dp[n]
assert Solution().longestCommonSubsequence("abcde", "ace") == 3
assert Solution().longestCommonSubsequence("abc", "def") == 0
class Solution {
public int longestCommonSubsequence(String a, String b) {
int m = a.length(), n = b.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
dp[i][j] = a.charAt(i - 1) == b.charAt(j - 1) ? dp[i - 1][j - 1] + 1 : Math.max(dp[i - 1][j], dp[i][j - 1]);
return dp[m][n];
}
}
func longestCommonSubsequence(text1 string, text2 string) int {
n := len(text2)
dp := make([]int, n+1) // one row of the LCS table
for i := 0; i < len(text1); i++ {
diag := 0
for j := 1; j <= n; j++ {
up := dp[j]
if text1[i] == text2[j-1] {
dp[j] = diag + 1
} else {
dp[j] = max(dp[j], dp[j-1])
}
diag = up
}
}
return dp[n]
}