Algo-Sim › Dynamic Programming

Longest Common Subsequence

Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input

Return the length of the longest sequence of characters that appears, in order but not necessarily together, in both strings.

Problem

Given two strings text1 and text2, return the length of their longest common subsequence: the longest sequence of characters that appears in both strings in the same order, though not necessarily side by side. Return 0 if they share nothing.

Constraints

Edge cases to test

Follow-up questions

How do you use O(min(m, n)) space?
Keep two rows (or one row plus the diagonal) of the shorter string.
How do you print the subsequence?
Walk back from dp[m][n]: diagonal on a match, otherwise toward the larger neighbour. That needs the full table.

Solution

Java

public int longestCommonSubsequence(String text1, String text2) {
    int m = text1.length(), n = text2.length();
    int[][] dp = new int[m + 1][n + 1];
    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            if (text1.charAt(i - 1) == text2.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 longest_common_subsequence(text1, text2):
    m, n = len(text1), len(text2)
    dp = [[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]:
                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++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int longestCommonSubsequence(string &text1, string &text2) {
        int m = int(text1.size()), n = int(text2.size());
        vector<vector<int>> dp = vector<vector<int>>(m + 1, vector<int>(n + 1));
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (text1[i - 1] == text2[j - 1]) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = std::max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        return dp[m][n];
    }
};

More Dynamic Programming problems