Longest Common Subsequence
Intermediate · 11 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
The longest common subsequence is the longest run of items that appear in both of two sequences in the same order, gaps allowed. A table compares the sequences prefix by prefix. It is the idea behind tools that show what changed between two versions.
Practical use cases
- Web app: Show changes between document versions. A CMS shows editors a "compare revisions" screen with removed lines in red and new lines in green. The code finds the longest set of lines that both versions share in order, and everything else is marked changed. A 500-line article is compared in a blink. Editors immediately see which paragraph was rewritten and which was untouched.
- Web app: Plagiarism or similarity score. A school portal gives a similarity percentage between two submitted answers by measuring the longest shared sequence of words. Reordered or padded copies still score high. Teachers see a score like 72 percent and the shared words highlighted, so they can quickly judge whether it is real copying or just a common phrase.
- System: git diff and DNA comparison. Version control tools use this idea to decide which lines of a file stayed, moved or changed. Biologists use it to compare gene sequences. In each of these, the table of shared lengths between two sequences tells the tool what stayed the same, and everything outside it is shown as changed.
The story: The Two Diaries
Mira and Kabir each kept a diary of what they ate during Diwali week. Mira wrote the letters of her sweets in order: A G C A T. Kabir's list was G A C. Their mother asked: "What is the longest list of sweets that appears in both diaries, in the same order?" Skipping is fine; swapping order is not.
Kabir tried every possible subset of his three letters and hunted in Mira's diary, which is slow. Mira had a better idea: "Let us compare only the first few letters of each diary, and grow the answer one letter at a time." She drew a table with Mira's letters down the side and Kabir's across the top.
In every cell she asked one question. Do the two newest letters match? If yes, the shared list grows by one on top of the diagonal answer. If not, one of the two letters has to be dropped, so she took the better of "drop Mira's letter" (the cell above) and "drop Kabir's letter" (the cell to the left). When the table was full, the bottom-right corner held the answer: 2. This is the Longest Common Subsequence.
How to spot this problem, and where you need it
You need to measure or display how much two sequences, such as two texts, files or lists, have in common while allowing extra items in between.
Signs you need it
- The problem says "common subsequence", "what stayed the same" or "diff" and the shared items must be in the same order.
- Plain equality checks only say "different" and cannot show where.
- A recursive comparison of two long texts becomes very slow because it repeats the same comparisons.
Where to use it in a project
- Revision history and compare screens in CMS, wiki and document tools.
- Similarity scoring in plagiarism, duplicate-content and merge features.
The solution
Build a table with one row per item of the first sequence and one column per item of the second. If the two items at a cell match, its value is the diagonal cell plus 1. If not, it is the larger of the cell above and the cell to the left. The bottom-right value is the length of the longest common subsequence. Walking back through the table shows exactly which items were shared.
Payoff: Before: checking every subset of lines, impossible for 500 lines. After: a table of 250,000 cells filled in milliseconds.
Explain it like I am 8
Two friends wrote the same story in slightly different ways. You want the longest bunch of words that both stories share in the same order, even if other words sit between them. You compare the stories a little at a time and write each partial answer in a grid.
How it works, step by step
- Draw a grid with one row per letter of word A and one column per letter of word B, plus an empty first row and column filled with 0.
- For each cell look at the two letters
a[i-1]andb[j-1]. - If they match:
dp[i][j] = dp[i-1][j-1] + 1(extend the diagonal answer). - If they differ:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])(drop one letter, keep the better). - The bottom-right cell is the length. To get the letters, walk from that corner back: on a match, take the letter and go diagonally; otherwise move toward the bigger neighbour.
The code in four languages
PHP
<?php
// Longest common subsequence of two strings: returns length and one example.
function lcs(string $a, string $b): array {
$m = strlen($a); $n = strlen($b);
$dp = array_fill(0, $m + 1, array_fill(0, $n + 1, 0)); // row 0 and column 0 stay 0
for ($i = 1; $i <= $m; $i++) {
for ($j = 1; $j <= $n; $j++) {
if ($a[$i - 1] === $b[$j - 1]) {
$dp[$i][$j] = $dp[$i - 1][$j - 1] + 1; // letters match: extend diagonal
} else {
$dp[$i][$j] = max($dp[$i - 1][$j], $dp[$i][$j - 1]); // drop one letter
}
}
}
// walk back from the corner to rebuild one longest common subsequence
$i = $m; $j = $n; $out = '';
while ($i > 0 && $j > 0) {
if ($a[$i - 1] === $b[$j - 1]) { $out = $a[$i - 1] . $out; $i--; $j--; }
elseif ($dp[$i - 1][$j] >= $dp[$i][$j - 1]) { $i--; }
else { $j--; }
}
return [$dp[$m][$n], $out];
}
[$len, $text] = lcs('AGCAT', 'GAC');
echo $len, ' ', $text, "\n"; // 2 GA (or AC)JavaScript
// Longest common subsequence of two strings: returns length and one example.
function lcs(a, b) {
const m = a.length, n = b.length;
const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0)); // row 0 and column 0 stay 0
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (a[i - 1] === b[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1; // letters match: extend diagonal
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); // drop one letter
}
}
}
// walk back from the corner to rebuild one longest common subsequence
let i = m, j = n, out = '';
while (i > 0 && j > 0) {
if (a[i - 1] === b[j - 1]) { out = a[i - 1] + out; i--; j--; }
else if (dp[i - 1][j] >= dp[i][j - 1]) { i--; }
else { j--; }
}
return [dp[m][n], out];
}
const [len, text] = lcs('AGCAT', 'GAC');
console.log(len + ' ' + text); // 2 GA (or AC)Java
public class Main {
// Longest common subsequence of two strings: prints length and one example.
static String lcs(String a, String b) {
int m = a.length(), n = b.length();
int[][] dp = new int[m + 1][n + 1]; // row 0 and column 0 stay 0
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] = dp[i - 1][j - 1] + 1; // letters match: extend diagonal
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); // drop one letter
}
}
}
// walk back from the corner to rebuild one longest common subsequence
int i = m, j = n;
StringBuilder out = new StringBuilder();
while (i > 0 && j > 0) {
if (a.charAt(i - 1) == b.charAt(j - 1)) { out.append(a.charAt(i - 1)); i--; j--; }
else if (dp[i - 1][j] >= dp[i][j - 1]) { i--; }
else { j--; }
}
return dp[m][n] + " " + out.reverse(); // we walked backwards
}
public static void main(String[] args) {
System.out.println(lcs("AGCAT", "GAC")); // 2 GA (or AC)
}
}Go
package main
import "fmt"
// Longest common subsequence of two strings: returns length and one example.
func lcs(a, b string) (int, string) {
m, n := len(a), len(b)
dp := make([][]int, m+1) // row 0 and column 0 stay 0
for i := range dp {
dp[i] = make([]int, n+1)
}
for i := 1; i <= m; i++ {
for j := 1; j <= n; j++ {
if a[i-1] == b[j-1] {
dp[i][j] = dp[i-1][j-1] + 1 // letters match: extend diagonal
} else {
dp[i][j] = max(dp[i-1][j], dp[i][j-1]) // drop one letter
}
}
}
// walk back from the corner to rebuild one longest common subsequence
i, j := m, n
out := ""
for i > 0 && j > 0 {
if a[i-1] == b[j-1] {
out = string(a[i-1]) + out
i--
j--
} else if dp[i-1][j] >= dp[i][j-1] {
i--
} else {
j--
}
}
return dp[m][n], out
}
func main() {
length, text := lcs("AGCAT", "GAC")
fmt.Println(length, text) // 2 GA (or AC)
}Time: O(m × n) · Extra space: O(m × n). One cell per pair of prefixes. If you only need the length, two rows are enough.
Watch out for
- Mixing up subsequence and substring. A subsequence may skip letters; a substring must be a solid block.
- Off-by-one between table indexes (1..m) and string indexes (0..m-1): compare a[i-1] with b[j-1].
- Forgetting the empty first row and column, so the first letters have nothing to look back at.
Quick check
- When the two current letters match, what do we do?
- Take the larger of above and left
- Add 1 to the diagonal cell
- Reset to 0
- AGCAT and GAC share a common subsequence of what length?
- 3
- 1
- 2
- Where is the final answer in the table?
- Bottom-right corner
- Top-left corner
- The largest cell anywhere