1. Home
  2. Design & Analysis of Algorithms
  3. Longest Common Subsequence (LCS)

Longest Common Subsequence (LCS)

Find the longest sequence of letters that appears, in order, in two strings. A classic dynamic programming problem behind diff tools and DNA comparison.

Interactive 3DIntermediate12 min readDAAUpdated

Drag to rotate · Right-drag to pan · Click, then scroll to zoom · Space play · Left arrowRight arrow step

What's happening

A subsequence keeps letters in order but may skip some ("ACE" is a subsequence of "ABCDE"). The Longest Common Subsequence of two strings is the longest one hidden in both. Used by diff, Git and DNA comparison. Press Solve.

Pseudocode

  1. for i ← 0 to m: dp[i][0] ← 0; for j ← 0 to n: dp[0][j] ← 0
  2. for i ← 1 to m:
  3. for j ← 1 to n:
  4. if A[i] == B[j]:
  5. dp[i][j] ← dp[i−1][j−1] + 1 // letters match: extend
  6. else:
  7. dp[i][j] ← max(dp[i−1][j], dp[i][j−1]) // drop one letter
  8. trace back from dp[m][n] to read the subsequence
Read this model as text · 45 steps

One run of the model above, written out step by step. Useful with a screen reader, on a slow connection, or for quick revision. The values may differ from the run on your screen.

  1. A subsequence keeps letters in order but may skip some ("ACE" is a subsequence of "ABCDE"). The Longest Common Subsequence of two strings is the longest one hidden in both. Used by diff, Git and DNA comparison. Press Solve.
  2. dp[i][j] = length of the longest common subsequence of the first i letters of A and the first j letters of B. An empty string has nothing in common, so row 0 and column 0 are 0.
  3. 'A' ≠ 'B'. Best of dropping a letter from A (above: 0) or from B (left: 0) → 0.
  4. 'A' ≠ 'D'. Best of dropping a letter from A (above: 0) or from B (left: 0) → 0.
  5. 'A' ≠ 'C'. Best of dropping a letter from A (above: 0) or from B (left: 0) → 0.
  6. A[1] = B[4] = 'A' — a match! Take the diagonal value and add 1: 0 + 1 = 1.
  7. 'A' ≠ 'B'. Best of dropping a letter from A (above: 0) or from B (left: 1) → 1.
  8. A[1] = B[6] = 'A' — a match! Take the diagonal value and add 1: 0 + 1 = 1.
  9. A[2] = B[1] = 'B' — a match! Take the diagonal value and add 1: 0 + 1 = 1.
  10. 'B' ≠ 'D'. Best of dropping a letter from A (above: 0) or from B (left: 1) → 1.
  11. 'B' ≠ 'C'. Best of dropping a letter from A (above: 0) or from B (left: 1) → 1.
  12. 'B' ≠ 'A'. Best of dropping a letter from A (above: 1) or from B (left: 1) → 1.
  13. A[2] = B[5] = 'B' — a match! Take the diagonal value and add 1: 1 + 1 = 2.
  14. 'B' ≠ 'A'. Best of dropping a letter from A (above: 1) or from B (left: 2) → 2.
  15. 'C' ≠ 'B'. Best of dropping a letter from A (above: 1) or from B (left: 0) → 1.
  16. 'C' ≠ 'D'. Best of dropping a letter from A (above: 1) or from B (left: 1) → 1.
  17. A[3] = B[3] = 'C' — a match! Take the diagonal value and add 1: 1 + 1 = 2.
  18. 'C' ≠ 'A'. Best of dropping a letter from A (above: 1) or from B (left: 2) → 2.
  19. 'C' ≠ 'B'. Best of dropping a letter from A (above: 2) or from B (left: 2) → 2.
  20. 'C' ≠ 'A'. Best of dropping a letter from A (above: 2) or from B (left: 2) → 2.
  21. A[4] = B[1] = 'B' — a match! Take the diagonal value and add 1: 0 + 1 = 1.
  22. 'B' ≠ 'D'. Best of dropping a letter from A (above: 1) or from B (left: 1) → 1.
  23. 'B' ≠ 'C'. Best of dropping a letter from A (above: 2) or from B (left: 1) → 2.
  24. 'B' ≠ 'A'. Best of dropping a letter from A (above: 2) or from B (left: 2) → 2.
  25. A[4] = B[5] = 'B' — a match! Take the diagonal value and add 1: 2 + 1 = 3.
  26. 'B' ≠ 'A'. Best of dropping a letter from A (above: 2) or from B (left: 3) → 3.
  27. 'D' ≠ 'B'. Best of dropping a letter from A (above: 1) or from B (left: 0) → 1.
  28. A[5] = B[2] = 'D' — a match! Take the diagonal value and add 1: 1 + 1 = 2.
  29. 'D' ≠ 'C'. Best of dropping a letter from A (above: 2) or from B (left: 2) → 2.
  30. 'D' ≠ 'A'. Best of dropping a letter from A (above: 2) or from B (left: 2) → 2.
  31. 'D' ≠ 'B'. Best of dropping a letter from A (above: 3) or from B (left: 2) → 3.
  32. 'D' ≠ 'A'. Best of dropping a letter from A (above: 3) or from B (left: 3) → 3.
  33. 'A' ≠ 'B'. Best of dropping a letter from A (above: 1) or from B (left: 0) → 1.
  34. 'A' ≠ 'D'. Best of dropping a letter from A (above: 2) or from B (left: 1) → 2.
  35. 'A' ≠ 'C'. Best of dropping a letter from A (above: 2) or from B (left: 2) → 2.
  36. A[6] = B[4] = 'A' — a match! Take the diagonal value and add 1: 2 + 1 = 3.
  37. 'A' ≠ 'B'. Best of dropping a letter from A (above: 3) or from B (left: 3) → 3.
  38. A[6] = B[6] = 'A' — a match! Take the diagonal value and add 1: 3 + 1 = 4.
  39. A[7] = B[1] = 'B' — a match! Take the diagonal value and add 1: 0 + 1 = 1.
  40. 'B' ≠ 'D'. Best of dropping a letter from A (above: 2) or from B (left: 1) → 2.
  41. 'B' ≠ 'C'. Best of dropping a letter from A (above: 2) or from B (left: 2) → 2.
  42. 'B' ≠ 'A'. Best of dropping a letter from A (above: 3) or from B (left: 2) → 3.
  43. A[7] = B[5] = 'B' — a match! Take the diagonal value and add 1: 3 + 1 = 4.
  44. 'B' ≠ 'A'. Best of dropping a letter from A (above: 4) or from B (left: 4) → 4.
  45. Length = 4. Walking back from the corner (diagonal steps are matches) spells out one LCS: "BCBA". Time and space O(m × n) = 42 cells.

Try this in the 3D model

  • Pause on a green "match" step. Which cell does the value come from?
  • Type your own two words and solve — e.g. your name and a friend's name.
  • Look at the 3D bars from the side. The heights only ever go up as you move right or down. Why?

What is a subsequence?

A subsequence keeps characters in their original order but may skip some. From "ABCDE":

  • "ACE" ✅ (skip B and D)
  • "AEC" ❌ (order changed)

A substring is stricter — it must be contiguous ("BCD").

The Longest Common Subsequence (LCS) of two strings is the longest subsequence that appears in both. For "ABCBDAB" and "BDCABA", one LCS is "BCBA" (length 4).

Why dynamic programming?

A string of length m has 2ᵐ subsequences — checking them all is hopeless. But the problem has optimal substructure: the LCS of two strings can be built from the LCS of their prefixes.

Let dp[i][j] = length of the LCS of the first i letters of A and the first j letters of B.

if A[i] == B[j]:   dp[i][j] = dp[i−1][j−1] + 1            (match: extend)
else:              dp[i][j] = max(dp[i−1][j], dp[i][j−1]) (drop a letter from A or B)

Base case: row 0 and column 0 are 0 (an empty string has nothing in common).

In the 3D model, a match lights up the diagonal cell (green), and a mismatch compares the cells above and to the left (yellow). Bar heights equal the LCS lengths, so the table looks like a staircase rising towards the far corner.

Reading the answer

dp[m][n] is the length. To get the actual subsequence, start at the bottom-right cell and walk back:

  • if the letters match, that letter is part of the LCS — move diagonally;
  • otherwise move to whichever neighbour (up or left) holds the bigger value.

Collect the matched letters in reverse.

Code

def lcs(A, B):
    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])
    # trace back
    i, j, out = m, n, []
    while i > 0 and j > 0:
        if A[i - 1] == B[j - 1]:
            out.append(A[i - 1]); i -= 1; j -= 1
        elif dp[i - 1][j] >= dp[i][j - 1]:
            i -= 1
        else:
            j -= 1
    return dp[m][n], "".join(reversed(out))

print(lcs("ABCBDAB", "BDCABA"))   # (4, 'BCBA')
print(lcs("AGGTAB", "GXTXAYB"))   # (4, 'GTAB')
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

int lcsLength(const string& A, const string& B) {
    int m = A.size(), n = B.size();
    vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
    for (int i = 1; i <= m; i++)
        for (int j = 1; j <= n; j++)
            dp[i][j] = (A[i - 1] == B[j - 1]) ? dp[i - 1][j - 1] + 1
                                              : max(dp[i - 1][j], dp[i][j - 1]);
    return dp[m][n];
}

int main() {
    cout << lcsLength("ABCBDAB", "BDCABA") << "\n";   // 4
}

Where is LCS used?

  • diff and Git: the lines that stay the same form an LCS; everything else is shown as added or removed.
  • Bioinformatics: comparing DNA and protein sequences.
  • Plagiarism detection and spell-checking (closely related to edit distance).
  • Longest common substring (contiguous) — similar table, but reset to 0 on a mismatch.
  • Edit distance (Levenshtein) — minimum insertions, deletions and substitutions to turn A into B.
  • Longest increasing subsequence — a single-sequence cousin.

Common mistakes

  • Confusing subsequence (gaps allowed) with substring (no gaps).
  • Indexing A[i] instead of A[i − 1] when the table has an extra row and column.
  • Expecting a unique answer — there can be several LCSs of the same length.

Complexity at a glance

Case / operationTimeWhy
Fill the tableO(m × n)One cell per pair of prefixes.
Trace backO(m + n)
Brute force (all subsequences)O(2ᵐ × n)
Extra spaceO(m × n)

Quick check

Test yourself — pick an answer to see if you got it.

1. Which of these is a subsequence of "ALGORITHM"?

2. If A[i] == B[j], then dp[i][j] equals…

3. What is the LCS length of "ABCBDAB" and "BDCABA"?

4. Which tool relies on the LCS idea?

Saved in this browser.
Spotted a mistake or a bug in the 3D model?

Report a mistake

in Longest Common Subsequence (LCS). Thank you — every report makes the lesson better for the next reader.

We'll also include a link to the step of the 3D model you're on and your browser type, so we can reproduce it.