9. Longest Common Subsequence

The algorithm behind diff and git diff

You run git diff and see green lines for additions, red lines for deletions, and unchanged lines in between. How does Git know which lines stayed the same? It finds the Longest Common Subsequence (LCS) of the old and new files. Everything in the LCS is unchanged; everything else is either an insertion or a deletion.

LCS is one of the most important algorithms in computer science. It powers diff and patch utilities, helps biologists align DNA sequences, and is a classic example of dynamic programming — closely related to the Levenshtein distance we covered earlier in this series.

Subsequence vs Substring

Before we dive in, there's a critical distinction to understand:

ConceptDefinitionExample from "ABCDE"
Substring A contiguous block of characters BCD, AB, CDE
Subsequence Characters in order, but not necessarily contiguous ACE, BD, ABDE

The key difference

A substring must be consecutive characters: you can't skip any. A subsequence can skip characters, but must preserve the original left-to-right order. Every substring is a subsequence, but not every subsequence is a substring.

Quick check

String:       A B C D E

Substring: B C D ✓ (positions 1,2,3 — contiguous) Subsequence: A C E ✓ (positions 0,2,4 — in order, gaps OK) Subsequence: E C A ✗ (out of order!) Subsequence: A B C D E ✓ (the full string is a subsequence of itself)

The Problem

Given two strings, find the longest sequence of characters that appears in both strings, in the same order, but not necessarily contiguously. This is the Longest Common Subsequence.

Example: LCS of "ABCBDAB" and "BDCAB"

String 1:  A B C B D A B
String 2:  B D C A B

LCS: B C A B (length 4)

Verify in String 1: A [B] [C] B D [A] [B] Verify in String 2: [B] D [C] [A] [B]

Both contain B, C, A, B in that order. ✓ No common subsequence of length 5 exists.

Note that the LCS is not necessarily unique — "BDAB" is another valid LCS of length 4 for these strings. The length is always unique, but there can be multiple subsequences that achieve it.

The Recursive Insight

Compare two strings X (length m) and Y (length n) starting from the end. At each step, there are exactly two cases:

The Core Recurrence

If the last characters match (X[m-1] == Y[n-1]), that character is part of the LCS. Include it and recurse on both strings with those characters removed.

If they don't match, the LCS does not use both last characters. Try skipping from each string and take the longer result:

  • Skip from X: LCS of X[0..m-1] and Y[0..n]
  • Skip from Y: LCS of X[0..m] and Y[0..n-1]

Pseudocode (Recursive)

function lcs(X, Y, i, j):
    if i == 0 or j == 0:
        return 0              // one string is empty — no common subsequence

    if X[i-1] == Y[j-1]:
        return 1 + lcs(X, Y, i-1, j-1)    // match! include it

    return max(
        lcs(X, Y, i-1, j),   // skip last char of X
        lcs(X, Y, i, j-1)    // skip last char of Y
    )

This works correctly, but it's exponentially slow — just like the naive Levenshtein recursion.

Why Naive Recursion Is Exponential

Overlapping subproblems

lcs("ABCB", "BDCA")
├── lcs("ABC", "BDCA")           ← skip from X
│   ├── lcs("AB", "BDCA")
│   │   ├── lcs("A", "BDCA")
│   │   └── lcs("AB", "BDC")    ← ★
│   └── lcs("ABC", "BDC")
│       ├── lcs("AB", "BDC")    ← ★  (same subproblem!)
│       └── lcs("ABC", "BD")
└── lcs("ABCB", "BDC")           ← skip from Y
    ├── lcs("ABC", "BDC")        ← ★  (again!)
    └── lcs("ABCB", "BD")
        └── ...

The subproblem lcs("AB", "BDC") and lcs("ABC", "BDC") each appear multiple times. In the full tree, the redundancy is catastrophic. The worst-case time complexity is O(2max(m,n)).

The fix is the same as with Levenshtein: dynamic programming. Solve each subproblem once, store the result in a table, and look it up whenever needed.

The Dynamic Programming Table

Build an (m+1) × (n+1) table where cell [i][j] holds the length of the LCS of the first i characters of X and the first j characters of Y.

  1. Initialize the borders

    Row 0: LCS of "" and any string is 0.
    Column 0: LCS of any string and "" is 0.
    So the entire first row and first column are filled with zeros.

  2. Fill left-to-right, top-to-bottom

    For each cell [i][j]:
    If X[i-1] == Y[j-1]: dp[i][j] = dp[i-1][j-1] + 1 (diagonal + 1).
    Otherwise: dp[i][j] = max(dp[i-1][j], dp[i][j-1]) (best of top or left).

  3. Read the answer

    The bottom-right cell dp[m][n] is the length of the LCS.

Worked Example: "ABCBDAB" and "BDCAB"

The completed DP table

        ""  B  D  C  A  B
    ""   0  0  0  0  0  0
     A   0  0  0  0  1  1
     B   0  1  1  1  1  2
     C   0  1  1  2  2  2
     B   0  1  1  2  2  3
     D   0  1  2  2  2  3
     A   0  1  2  2  3  3
     B   0  1  2  2  3  4

The bottom-right cell is 4 — the LCS has length 4.

Let's trace how a few cells were filled:

Cell [2][1]: comparing "AB" vs "B"

X[1] = 'B',  Y[0] = 'B'  →  they match!
dp[2][1] = dp[1][0] + 1 = 0 + 1 = 1

Cell [3][3]: comparing "ABC" vs "BDC"

X[2] = 'C',  Y[2] = 'C'  →  they match!
dp[3][3] = dp[2][2] + 1 = 1 + 1 = 2

Cell [4][4]: comparing "ABCB" vs "BDCA"

X[3] = 'B',  Y[3] = 'A'  →  mismatch
dp[4][4] = max(dp[3][4], dp[4][3]) = max(2, 2) = 2

Cell [7][5]: comparing "ABCBDAB" vs "BDCAB"

X[6] = 'B',  Y[4] = 'B'  →  they match!
dp[7][5] = dp[6][4] + 1 = 3 + 1 = 4

Backtracking: Recovering the Actual LCS

The DP table tells you the length of the LCS, but not which characters are in it. To recover the actual subsequence, trace backward from dp[m][n] to dp[0][0]:

  1. Start at dp[m][n]

    Begin in the bottom-right corner of the table.

  2. If characters match

    X[i-1] == Y[j-1]: this character is in the LCS. Record it, move diagonally to dp[i-1][j-1].

  3. If characters don't match

    Move to whichever neighbor is larger: dp[i-1][j] (up) or dp[i][j-1] (left). If they're equal, either choice gives a valid LCS.

  4. Stop at row 0 or column 0

    Reverse the collected characters — that's your LCS.

Backtracking "ABCBDAB" vs "BDCAB"

dp[7][5]=4  X[6]='B', Y[4]='B' → match! Record 'B', move to dp[6][4]
dp[6][4]=3  X[5]='A', Y[3]='A' → match! Record 'A', move to dp[5][3]
dp[5][3]=2  X[4]='D', Y[2]='C' → mismatch, dp[4][3]=2, dp[5][2]=2
            tie → go up to dp[4][3]
dp[4][3]=2  X[3]='B', Y[2]='C' → mismatch, dp[3][3]=2 > dp[4][2]=1
            go up to dp[3][3]
dp[3][3]=2  X[2]='C', Y[2]='C' → match! Record 'C', move to dp[2][2]
dp[2][2]=1  X[1]='B', Y[1]='D' → mismatch, dp[1][2]=0, dp[2][1]=1
            go left to dp[2][1]
dp[2][1]=1  X[1]='B', Y[0]='B' → match! Record 'B', move to dp[1][0]
dp[1][0]=0  → row or column is 0, stop.

Collected (reversed): B, C, A, B → LCS = "BCAB"

The Complete Algorithm

DP Table Fill

function lcsLength(X, Y):
    m = length(X)
    n = length(Y)

    // Create (m+1) × (n+1) table
    dp = new array[m+1][n+1]

    // Base cases: first row and column are all 0
    for i from 0 to m: dp[i][0] = 0
    for j from 0 to n: dp[0][j] = 0

    // Fill the table
    for i from 1 to m:
        for j from 1 to n:
            if X[i-1] == Y[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

Backtrack to Recover the LCS

function backtrackLCS(dp, X, Y):
    lcs = ""
    i = length(X)
    j = length(Y)

    while i > 0 and j > 0:
        if X[i-1] == Y[j-1]:
            lcs = X[i-1] + lcs       // prepend the character
            i = i - 1
            j = j - 1
        else if dp[i-1][j] >= dp[i][j-1]:
            i = i - 1                // move up
        else:
            j = j - 1                // move left

    return lcs

Connection to Diff

The diff utility — and by extension git diff — works on exactly this principle. When comparing two files line by line:

LCS = what stays the same

The LCS of the old and new file (treating each line as a "character") represents the lines that are unchanged. Everything in the old file but not in the LCS is a deletion. Everything in the new file but not in the LCS is an insertion.

Diff as LCS

Old file (lines):     A  B  C  D  E  F
New file (lines):     A  C  D  G  E  F

LCS: A C D E F

Diff output: A (unchanged — in LCS)

  • B (deleted — in old, not in LCS) C (unchanged) D (unchanged)
  • G (inserted — in new, not in LCS) E (unchanged) F (unchanged)

Real diff tools use optimizations (like Myers' diff algorithm, which finds the shortest edit script in O(ND) time where D is the number of differences), but the core idea is the same: find what's common, and everything else is a change.

Complexity

Time and Space

Time: O(m × n) — we fill every cell in the table exactly once.
Space: O(m × n) for the full table (needed if you want to backtrack).
Space: O(min(m, n)) if you only need the length — keep just two rows at a time, since each row depends only on the previous one.

For two strings of length 1,000, that's 1,000,000 cells — trivial for a modern computer. For two files of 10,000 lines each, it's 100 million cells — still feasible, though real diff tools use smarter algorithms to handle large files efficiently.

Where LCS Is Used

Application How it uses LCS
diff / patch Find unchanged lines between two file versions; everything else is +/-
Version control (Git) git diff, merge conflict detection, and blame all rely on LCS-based algorithms
Bioinformatics Sequence alignment of DNA, RNA, and proteins to find conserved regions
Plagiarism detection Find the longest shared passage between two documents
File synchronization rsync-like tools use LCS ideas to minimize data transfer
Spell checking LCS length as a similarity metric between words

Key Takeaways

  • A subsequence preserves order but can skip characters; a substring must be contiguous
  • LCS finds the longest sequence of characters common to both strings (in order)
  • The naive recursive solution is exponential due to overlapping subproblems — the same pattern as Levenshtein distance
  • Dynamic programming solves it in O(m × n) time by filling a 2D table bottom-up
  • Each cell depends on two neighbors (top and left) for mismatches, or the diagonal for matches
  • Backtracking through the table recovers the actual subsequence, not just its length
  • The LCS is the foundation of diff: what's common stays, everything else is an insertion or deletion
  • Space can be reduced to O(min(m, n)) if only the length is needed

The Longest Common Subsequence is a beautiful example of how a simple recurrence — match or skip — can be turned into an efficient algorithm through dynamic programming. The same table-filling pattern appears throughout algorithm design, from edit distance to sequence alignment to the knapsack problem. And every time you run git diff, you're relying on this very idea.