SDE & MLE Prep

1143. Longest Common Subsequence

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]