Longest Common Substring
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
The longest common substring is the longest unbroken stretch of characters that appears in both texts. Unlike a subsequence, no gaps are allowed, so the count restarts at zero whenever characters stop matching. It finds copied chunks of text.
Practical use cases
- Web app: Spotting copied paragraphs. A college assignment portal flags essays that share a long unbroken run of words with another submission. The checker finds the longest identical stretch between two essays, and a run of 40 words in a row is highlighted for the teacher. A single shared sentence from a textbook is ignored, which keeps teachers from chasing false alarms.
- Web app: Duplicate product listing finder. A marketplace wants to catch sellers who copy another seller's description. It compares the texts and reports the longest shared stretch. A long exact match is a strong sign of a copy. Moderators get a short list of listings with a long identical stretch, so they review ten likely copies instead of a thousand random listings every week.
- System: Malware and genome matching. Antivirus tools look for known code fragments inside files, and genetic software looks for shared DNA stretches. Both rely on finding the longest exact shared piece. In each of these, the count restarts at zero whenever characters stop matching, so only the longest unbroken stretch survives, and the table finds it in a single pass.
The story: MANGO and TANGO
Grandpa Bhaskar loved word games. One evening he wrote two words on the veranda slate: MANGO and TANGO. "Find the longest piece that appears in both words," he said. "But the piece must be unbroken, no skipping letters." Mira remembered the diary puzzle from before, where skipping was allowed, and wondered what changes.
She drew the same table with one tiny change. If two letters match, the cell grows by one over the diagonal, as before. But if two letters differ, the shared block is broken and the cell resets to 0. There is no "take the better of above and left" any more, because a block cannot jump over a mismatch.
Now the answer is no longer in the corner. Mira scanned the whole table for the biggest number. It was 4, sitting under the final O of the shared block "ANGO". Grandpa clapped. That is the Longest Common Substring: the same table as subsequences, but with resets and a hunt for the maximum.
How to spot this problem, and where you need it
You want to know the longest piece of text that appears exactly the same in two different texts, with no gaps or changes in between.
Signs you need it
- The problem says "substring", "contiguous" or "unbroken" and asks for the longest shared piece.
- You are detecting copy-paste, duplicate content or a known signature inside bigger text.
- Comparing every start position of one text against every start position of the other is very slow.
Where to use it in a project
- Plagiarism and duplicate-content checks in portals and marketplaces.
- Scanning uploaded files or text for known signature fragments.
The solution
Make a table with one row per character of the first text and one column per character of the second. If the two characters match, the cell is the diagonal cell plus 1; if not, it is 0. Keep track of the largest value seen anywhere in the table and where it was. That value is the length of the longest shared stretch, and its position tells you the text itself.
Payoff: Before: comparing every pair of start positions and lengths, billions of checks for long essays. After: one pass over a table, roughly 1 million cells for two 1,000-letter texts.
Explain it like I am 8
Two necklaces have coloured beads. You want the longest unbroken stretch of beads that looks the same on both. As soon as the beads stop matching, you start counting again from zero. You remember the longest stretch you saw.
How it works, step by step
- Draw the grid like for subsequences: a row per letter of A, a column per letter of B, edges zero.
- If the two letters match:
dp[i][j] = dp[i-1][j-1] + 1. - If they differ:
dp[i][j] = 0. The block is broken, so we start over. - Keep a record of the biggest value you ever write, and where. Do not just read the corner.
- The substring itself ends at that best cell and is as long as the number in it.
The code in four languages
PHP
<?php
// Longest common substring (unbroken block) of two strings.
function longestCommonSubstring(string $a, string $b): string {
$m = strlen($a); $n = strlen($b);
$dp = array_fill(0, $m + 1, array_fill(0, $n + 1, 0));
$best = 0; $endInA = 0; // remember the biggest block and where it ends
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; // block grows
if ($dp[$i][$j] > $best) { $best = $dp[$i][$j]; $endInA = $i; }
} else {
$dp[$i][$j] = 0; // block broken: start again
}
}
}
return substr($a, $endInA - $best, $best);
}
echo longestCommonSubstring('MANGO', 'TANGO'), "\n"; // ANGOJavaScript
// Longest common substring (unbroken block) of two strings.
function longestCommonSubstring(a, b) {
const m = a.length, n = b.length;
const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
let best = 0, endInA = 0; // remember the biggest block and where it ends
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; // block grows
if (dp[i][j] > best) { best = dp[i][j]; endInA = i; }
} else {
dp[i][j] = 0; // block broken: start again
}
}
}
return a.slice(endInA - best, endInA);
}
console.log(longestCommonSubstring('MANGO', 'TANGO')); // ANGOJava
public class Main {
// Longest common substring (unbroken block) of two strings.
static String longestCommonSubstring(String a, String b) {
int m = a.length(), n = b.length();
int[][] dp = new int[m + 1][n + 1];
int best = 0, endInA = 0; // remember the biggest block and where it ends
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; // block grows
if (dp[i][j] > best) { best = dp[i][j]; endInA = i; }
} else {
dp[i][j] = 0; // block broken: start again
}
}
}
return a.substring(endInA - best, endInA);
}
public static void main(String[] args) {
System.out.println(longestCommonSubstring("MANGO", "TANGO")); // ANGO
}
}Go
package main
import "fmt"
// Longest common substring (unbroken block) of two strings.
func longestCommonSubstring(a, b string) string {
m, n := len(a), len(b)
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, n+1)
}
best, endInA := 0, 0 // remember the biggest block and where it ends
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 // block grows
if dp[i][j] > best {
best, endInA = dp[i][j], i
}
} else {
dp[i][j] = 0 // block broken: start again
}
}
}
return a[endInA-best : endInA]
}
func main() {
fmt.Println(longestCommonSubstring("MANGO", "TANGO")) // ANGO
}Time: O(m × n) · Extra space: O(m × n), or O(n) with two rows. One cell per pair of letters; each cell only looks at its diagonal neighbour.
Watch out for
- Copying the subsequence rule (max of above and left) instead of resetting to 0 on a mismatch.
- Reading the bottom-right corner as the answer. The best block can end anywhere, so track the maximum.
- Confusing the two: a substring is unbroken, a subsequence may skip letters.
Quick check
- What does a cell hold when the two letters differ?
- The max of above and left
- 0
- The diagonal value
- Where is the answer?
- Bottom-right corner
- First row
- The largest value anywhere in the table
- Longest common substring of MANGO and TANGO?
- ANGO
- MANGO
- NGO only