Longest Common Subsequence

medium2D Dynamic Programming60 stepsJava · Python · C++

Find the length of the longest sequence that appears in both strings in order (not necessarily contiguous). dp[i][j] is the LCS of the first i and first j characters. Matching characters extend the diagonal; otherwise take the better of dropping one character from either string.

▶ Watch the animated trace

Traced input: text1 = "abcde", text2 = "ace" → 3. Original problem: neetcode.io/problems/longest-common-subsequence

Complexity

BestO(m·n)
AverageO(m·n)
WorstO(m·n)
SpaceO(m·n)

Can be reduced to O(min(m, n)) with two rows.

Key idea

Common mistakes

Solution

Java
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++) {
            if (a.charAt(i - 1) == b.charAt(j - 1)) {
                dp[i][j] = dp[i - 1][j - 1] + 1;
            } else {
                dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
            }
        }
    }
    return dp[m][n];
}
Python
def longestCommonSubsequence(a: str, b: str) -> int:
    m, n = len(a), len(b)
    dp = [[0] * (n + 1) for _ in range(m + 1)]
    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] + 1
            else:
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
    return dp[m][n]
C++
int longestCommonSubsequence(string a, string b) {
    int m = a.size(), n = b.size();
    vector<vector<int>> dp(m + 1, vector<int>(n + 1));
    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            if (a[i - 1] == b[j - 1]) {
                dp[i][j] = dp[i - 1][j - 1] + 1;
            } else {
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
            }
        }
    }
    return dp[m][n];
}

Edge cases

Each one has its own trace in the interactive view.

CaseInputAnswer
No common characters
Every cell stays 0.
text1 = "abc", text2 = "def"0
Identical
The whole diagonal matches.
text1 = "abc", text2 = "abc"3
Order matters
Either 'a' or 'b', not both in order.
text1 = "ab", text2 = "ba"1
← Minimum Path SumPartition Equal Subset Sum →