Skip to lesson

Longest common subsequence

Longest Common Subsequence (LCS) finds the longest sequence appearing in order in two strings. We start with plain recursion to see why string comparisons branch exponentially.

Brute Force Recursion and Why It Is Slow

A subsequence keeps some characters of a string in their original order, not necessarily next to each other; 'ace' is a subsequence of 'abcde'.

Given two strings s1 and s2, a common subsequence keeps characters in the same relative order but need not be next to each other. The LCS of 'abcde' and 'ace' is 'ace' (length 3).

Step by step

Step 1 of 7

Rowac
000
a000
b000
c000
s1
abc
s2
ac
Row 0 and Col 0 set to 0: comparing any prefix against an empty string gives LCS length 0.

Example 1 · LCS, Plain Recursion: O(2^(m+n)) Time

LcsRecursion.javaJava
public class LcsRecursion {    static int calls = 0;
    public static int lcs(String a, String b, int i, int j) {        calls++;        if (i == a.length() || j == b.length()) return 0;        if (a.charAt(i) == b.charAt(j)) {            return 1 + lcs(a, b, i + 1, j + 1);        }        return Math.max(lcs(a, b, i + 1, j), lcs(a, b, i, j + 1));    }
    public static void main(String[] args) {        System.out.println("LCS length: " + lcs("AGGTAB", "GXTXAYB", 0, 0));        System.out.println("Calls made: " + calls);    }}
Output
LCS length: 4
Calls made: 1079

What this code does

  • A match moves both positions on; a mismatch tries skipping a character from either string.
  • Two short strings of 6 and 7 characters already need 1,079 calls, because the same pair (i, j) is reached again and again.
  • For 20-character strings the call count would pass a trillion.

Example 2 · LCS, Memoization: O(m x n) Time, O(m x n) Space

LcsMemo.javaJava
import java.util.Arrays;
public class LcsMemo {    static int calls = 0;
    public static int lcs(String a, String b, int i, int j, int[][] memo) {        calls++;        if (i == a.length() || j == b.length()) return 0;        if (memo[i][j] != -1) return memo[i][j];        if (a.charAt(i) == b.charAt(j)) {            memo[i][j] = 1 + lcs(a, b, i + 1, j + 1, memo);        } else {            memo[i][j] = Math.max(lcs(a, b, i + 1, j, memo), lcs(a, b, i, j + 1, memo));        }        return memo[i][j];    }
    public static void main(String[] args) {        String a = "AGGTAB", b = "GXTXAYB";        int[][] memo = new int[a.length()][b.length()];        for (int[] row : memo) Arrays.fill(row, -1);        System.out.println("LCS length: " + lcs(a, b, 0, 0, memo));        System.out.println("Calls made: " + calls);    }}
Output
LCS length: 4
Calls made: 68

What this code does

  • memo[i][j] stores the LCS length of the suffixes starting at i and j; -1 means not computed yet.
  • There are only 6 x 7 = 42 pairs, so calls fall from 1,079 to 68.
  • The cost is an m by n memo table plus recursion depth up to m + n.

With plain recursion, we compare s1[i] and s2[j]. If they match: 1 + lcs(i + 1, j + 1). If they mismatch, we branch into two choices: skip s1[i] or skip s2[j], taking Math.max(lcs(i + 1, j), lcs(i, j + 1)).

Why is this slow? When no characters match, the function branches twice at every step, creating an exponential O(2^(m + n)) tree. For two 20-character strings, 2^40 is over 1 trillion calls! But many branches compare the exact same suffix pair (i, j), repeating identical work.

Constructing the 2D LCS Table

Define dp[i][j] as the LCS length of prefixes s1[0..i-1] and s2[0..j-1]. Table size is (m + 1) by (n + 1) where row 0 and col 0 represent empty prefixes.

Example 3 · LCS, 2D Table: O(m x n) Time, O(m x n) Space

LCSLengthDemo.javaJava
public class LCSLengthDemo {    public static int longestCommonSubsequence(String text1, String text2) {        int m = text1.length();        int 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] = 1 + dp[i - 1][j - 1];                } else {                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);                }            }        }        return dp[m][n];    }
    public static void main(String[] args) {        System.out.println("LCS of abcde and ace: " + longestCommonSubsequence("abcde", "ace"));        System.out.println("LCS of abc and def: " + longestCommonSubsequence("abc", "def"));    }}
Output
LCS of abcde and ace: 3
LCS of abc and def: 0

What this code does

  • The loops fill the table from the smallest prefixes upwards, so each cell reads neighbours that are already done: no recursion needed.
  • Characters 'a', 'c', 'e' match sequentially, yielding length 3.
  • Strings 'abc' and 'def' share no common characters, returning 0.

When characters match (s1[i - 1] == s2[j - 1]): dp[i][j] = 1 + dp[i - 1][j - 1] (look diagonally up-left). When characters mismatch: dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]) (take best from top or left). Filling the table takes O(m * n) time and O(m * n) space.

Fix the error

Fix the table size

The program crashes. Choose the replacement for line 3.

lcs("abcde", "ace") should return 3, but it crashes. Choose the line that fixes it.

public static int lcs(String a, String b) {
int m = a.length(), n = b.length();
int[][] dp = new int[m][n];
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] = 1 + dp[i - 1][j - 1];
else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
return dp[m][n];
}

Error

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

Reconstructing and Printing the Subsequence

The bottom-right cell dp[m][n] gives the LCS length. To reconstruct the actual text, backtrack from (m, n) back to (0, 0).

Example 4 · Reconstructing the Actual LCS String

LCSPrintDemo.javaJava
public class LCSPrintDemo {    public static String printLCS(String text1, String text2) {        int m = text1.length();        int 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] = 1 + dp[i - 1][j - 1];                } else {                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);                }            }        }        StringBuilder sb = new StringBuilder();        int i = m, j = n;        while (i > 0 && j > 0) {            if (text1.charAt(i - 1) == text2.charAt(j - 1)) {                sb.append(text1.charAt(i - 1));                i--;                j--;            } else if (dp[i - 1][j] > dp[i][j - 1]) {                i--;            } else {                j--;            }        }        return sb.reverse().toString();    }
    public static void main(String[] args) {        System.out.println("LCS string: " + printLCS("abcde", "ace"));    }}
Output
LCS string: ace

What this code does

  • Backtracks diagonally on character matches and adds them to builder.
  • Moves up or left according to the larger adjacent DP value on mismatch.
  • Reverses the accumulated string to produce original forward order 'ace'.

Example 5 · LCS, Two Rows: O(m x n) Time, O(n) Space

LCSOptimizedDemo.javaJava
public class LCSOptimizedDemo {    public static int lcsSpaceOpt(String text1, String text2) {        int m = text1.length();        int n = text2.length();        int[] prev = new int[n + 1];        int[] cur = new int[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)) {                    cur[j] = 1 + prev[j - 1];                } else {                    cur[j] = Math.max(prev[j], cur[j - 1]);                }            }            int[] temp = prev;            prev = cur;            cur = temp;        }        return prev[n];    }
    public static void main(String[] args) {        System.out.println("Opt LCS: " + lcsSpaceOpt("AGGTAB", "GXTXAYB"));    }}
Output
Opt LCS: 4

What this code does

  • Maintains only two rows of length n + 1 representing current and previous step.
  • Swaps references after each outer iteration, consuming only O(n) memory.
  • Longest common subsequence 'GTAB' has length 4.

If s1[i - 1] == s2[j - 1], this character was part of the LCS; append it to our list and step diagonally to (i - 1, j - 1). If they mismatch, move to whichever neighbor held the larger value: (i - 1, j) or (i, j - 1). Reversing the collected characters yields the exact LCS string.

Order of execution

Order the backtrack

Tap the five steps for printing the LCS in the order you do them.

Real-World Applications: Diff and DNA Alignment

The longest common subsequence (LCS) is the engine behind git diff, document change tracking, and computational biology: every character outside the LCS is an edit.

Java
String s1 = "ABCBDAB", s2 = "BDCABA";  // LCS "BCBA" has length 4int lcs = 4;int deletions = s1.length() - lcs;     // 3 characters removed from s1int insertions = s2.length() - lcs;    // 2 characters added from s2int minEdits = deletions + insertions; // 7 + 6 - 2 * 4 = 5

To transform s1 into s2 with minimal insertions and deletions, the minimum edits required is exactly (m + n - 2 * LCS).

Unmatched characters in s1 represent deletions, while unmatched characters in s2 represent additions.

Next step

Check your understanding

10 quick questions