Video in progress

Strong Middle 🧠 Problem solving

How do you find the longest common subsequence (LCS) of two strings with DP, and how do you reduce memory?

dp[i][j] is the LCS length for the first i characters of one string and the first j of the other. If the characters are equal, it's the diagonal plus 1; otherwise the larger of the top and left values. Time is O(n·m), and memory can be cut to two rows, which is O(min(n,m)).

📖 Answer

It's a subsequence, not a substring: the characters don't have to be consecutive, only the order is kept. For "abcde" and "ace" the answer is 3.

static int lcs(String a, String b) {
    if (a.length() < b.length()) { String t = a; a = b; b = t; } // b is the shorter one
    int[] prev = new int[b.length() + 1];
    int[] cur = new int[b.length() + 1];
    for (int i = 1; i <= a.length(); i++) {
        for (int j = 1; j <= b.length(); j++) {
            cur[j] = a.charAt(i - 1) == b.charAt(j - 1)
                    ? prev[j - 1] + 1
                    : Math.max(prev[j], cur[j - 1]);
        }
        int[] t = prev; prev = cur; cur = t;   // swap the rows
    }
    return prev[b.length()];
}

Each cell looks only at its top, left and diagonal neighbors, so there is no need to keep the whole table.

But there's a catch: if you need the sequence itself and not just the length, two rows aren't enough, because walking backward needs the full table. If both strings are 10⁵ characters, the table is 10¹⁰ cells and doesn't fit. For that case there is Hirschberg's algorithm: divide and conquer with O(n·m) time and O(min) memory.

A practical relative of LCS is diff. Git and other diff tools use Myers' algorithm, which is much faster on similar files.

Edit distance (Levenshtein) is almost the same table, just with the costs of three operations.