Sub topic 14
Contrast: Longest Common Substring
This chapter assumes you already know the LCS recurrence, the bottom-up DP table from earlier chapters, and the two-row space trick. It looks at a closely related problem that is easy to confuse with LCS: the longest common substring. The two problems use almost the same table, but one changed line in the recurrence leads to different answers, a different place to read the result, and different best-known algorithms.
The Problem Statement
A substring is a contiguous run of characters. A subsequence only has to keep the characters in order. The longest common substring of a and b is the longest string that appears as an unbroken block in both.
Take the running example, "ABCBDAB" and "BDCABA":
- An LCS has length 4.
"BCBA"is one example. Its characters are spread out in both strings. - The longest common substring has length 2. Both
"AB"and"BD"appear intact in each string, and no 3-character block is shared.
Every substring is also a subsequence, so the longest common substring can never be longer than the LCS. It is often much shorter.
Changing the Recurrence
In LCS, dp[i][j] is the LCS length of the prefixes a[:i] and b[:j]. A mismatch at a[i-1] and b[j-1] lets you drop one character and keep the best result so far, which is where max(dp[i-1][j], dp[i][j-1]) comes from.
That rule breaks for substrings. A shared block cannot skip characters, so a mismatch ends the current run. The table therefore has to mean something narrower:
> dp[i][j] is the length of the longest common suffix of a[:i] and b[:j], meaning the longest block that ends exactly at a[i-1] and exactly at b[j-1].
With that meaning, the recurrence is:
- If
a[i-1] == b[j-1]:dp[i][j] = dp[i-1][j-1] + 1, because the match extends the block ending one step earlier on the diagonal. - Otherwise:
dp[i][j] = 0, because no common block can end at two different characters.
Every common substring ends somewhere, so the answer is the maximum over all cells. It is not dp[m][n]. The bottom-right cell only describes blocks that end at the last character of both strings.
Implementation with Reconstruction
The substring itself is easy to recover, so you don't need a traceback walk. A common substring is one diagonal run. If you record where the best run ends and how long it is, you can slice it straight out of a.
def longest_common_substring(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
best_len, best_end = 0, 0 # best_end is an index into a (exclusive)
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
if dp[i][j] > best_len:
best_len = dp[i][j]
best_end = i
# else: dp[i][j] stays 0
return a[best_end - best_len:best_end]
result = longest_common_substring("ABCBDAB", "BDCABA")
print(result, len(result)) # AB 2Ties are settled by the strict > comparison, which keeps the first maximal run found in row-major order. Here that run is "AB", ending at a[1]. The block "BD" is just as long but is found later. Changing the test to >= would keep the last maximal run instead. As with LCS, the problem can have several correct answers, and your tie-breaking rule picks one.
Two Rows Are Enough Here Too
Each cell reads only the cell diagonally above-left, so the two-row trick from the earlier chapter still works. You can even recover the substring this way, because best_end and best_len hold everything the slice needs. In LCS, the two-row version loses the ability to trace back. In the substring version, you only lose the full table, which you never needed anyway.
def longest_common_substring_two_rows(a, b):
prev = [0] * (len(b) + 1)
best_len, best_end = 0, 0
for i, x in enumerate(a, 1):
curr = [0] * (len(b) + 1) # fresh zeros: a mismatch must read as 0
for j, y in enumerate(b, 1):
if x == y:
curr[j] = prev[j - 1] + 1
if curr[j] > best_len:
best_len, best_end = curr[j], i
prev = curr
return a[best_end - best_len:best_end]
print(longest_common_substring_two_rows("ABCBDAB", "BDCABA")) # ABThis uses O(mn) time and O(n) extra space. To get O(min(m, n)) space, swap the inputs so that b is the shorter string. If you do, slice the result from whichever string ends up in the outer loop.
Checking Against Brute Force
For short strings, you can enumerate every substring of a and test whether it appears in b. The check is slow, but its correctness is obvious, which makes it a good reference.
import random
def brute_force_substring_length(a, b):
best = 0
for i in range(len(a)):
for j in range(i + 1, len(a) + 1):
if j - i > best and a[i:j] in b:
best = j - i
return best
for _ in range(2000):
a = "".join(random.choice("AB") for _ in range(random.randint(0, 8)))
b = "".join(random.choice("AB") for _ in range(random.randint(0, 8)))
got = longest_common_substring_two_rows(a, b)
assert len(got) == brute_force_substring_length(a, b)
assert got in a and got in b
print("all checks passed")The test uses a two-letter alphabet on purpose. Small alphabets create many partial matches and broken runs, so they exercise the reset-to-zero path much more than random English text would. Empty strings are included too. They should return "" without raising an error.
Side-by-Side Comparison
| Aspect | Longest common subsequence | Longest common substring |
|---|---|---|
| Meaning of `dp[i][j]` | LCS of prefixes `a[:i]`, `b[:j]` | Longest common suffix of `a[:i]`, `b[:j]` |
| On mismatch | `max(dp[i-1][j], dp[i][j-1])` | `0` |
| Where the answer is | `dp[m][n]` | Maximum over all cells |
| Recovering the result | Traceback through the full table | Slice using the recorded end index and length |
| Two-row version | Gives the length only (Hirschberg needed for the string) | Gives the length and the string |
| Example answer | `"BCBA"`, length 4 | `"AB"`, length 2 |
| Best known time | O(mn), with small log-factor improvements | O(m + n) with suffix structures |
Where the Two Problems Really Differ
The DP tables cost the same, O(mn), but the problems are not equally hard.
Longest common substring has linear-time solutions. You build a generalized suffix tree, or a suffix automaton, for the two strings. Then you find the deepest node whose subtree contains suffixes from both strings. Another practical method is binary search on the answer length combined with rolling hashes. It checks a candidate length L by hashing every length-L window of a and probing a set of those hashes with the windows of b. The expected running time is O((m + n) log min(m, n)). Contiguity makes these methods possible. A shared block corresponds to a shared path in a suffix structure, and a fixed-length window can be hashed.
For LCS, nobody has found a comparable shortcut. Under the Strong Exponential Time Hypothesis, a widely believed conjecture in complexity theory, no algorithm computes LCS in O(n^(2−ε)) time for any ε > 0. This result comes from conditional lower bounds published in 2015 by Abboud, Backurs and Vassilevska Williams, and by Bringmann and Künnemann. The quadratic DP is close to the best you can do in the worst case.
Use these criteria to choose between the problems:
- Choose longest common substring when the shared material must stay intact. Examples are detecting copied code blocks, finding a shared motif, or locating overlaps between DNA reads. For long inputs, switch to suffix structures or hashing.
- Choose LCS when gaps are allowed and order is what matters. Examples are line-based diffs, aligning edited versions of a file, and edit-distance-style comparison.
Exercise
For a = "ACBD" and b = "ABCD", what are the longest common substring and the LCS length? Explain why they differ.
Show answer
The longest common substring has length 1. The adjacent pairs in a are AC, CB and BD, and the pairs in b are AB, BC and CD, so no 2-character block is shared, and any single shared letter, such as "A", is an answer. The LCS has length 3, for example "ABD" or "ACD", because the matched letters can skip over C or B. The substring version resets to 0 at every mismatch, so it never joins the separated matches.
Exercise
A colleague changes longestcommonsubstringtworows to return prev[-1] and uses one shared row, updated in place, with no reset on mismatch. Give an input where this goes wrong and say why.
Show answer
Try a = "ABX" and b = "ABY". The true answer has length 2 ("AB"). The last characters X and Y don't match, so the bottom-right cell describes a block ending at X and Y. Its correct value is 0, which shows that returning prev[-1] loses the answer. Without the reset, the cell instead keeps a stale value carried over from the row above. Either way the result is wrong. You must keep a running maximum, and every mismatched cell must read as 0.
Exercise
The longest common substring length is always at most the LCS length. When are they equal?
Show answer
They are equal exactly when some longest common subsequence happens to be contiguous in both strings. One case is when one string is a substring of the other, such as "BCD" and "ABCDE", where both answers have length 3. Since every common substring is a common subsequence, equality means that no gapped subsequence beats the best contiguous one.