Sub topic 14
Contrast: Longest Common Substring
This chapter assumes you know the bottom-up LCS table from earlier chapters, the difference between a subsequence and a substring, and basic Big-O notation.
The longest common substring problem sounds almost identical to LCS. The difference is that the shared characters must be contiguous in both strings. That one change alters the recurrence, the place where the answer sits in the table, and the result.
Same Inputs, Different Answers
Take the running example "ABCBDAB" and "BDCABA". Their LCS has length 4 (for example "BCBA"). Their longest common substring is only length 2. Both "AB" and "BD" appear as unbroken runs in each string, and no run of length 3 is shared.
| Property | Longest common subsequence | Longest common substring |
|---|---|---|
| Characters must be adjacent | No | Yes |
| Meaning of `dp[i][j]` | LCS length of prefixes `a[:i]`, `b[:j]` | Length of common run **ending exactly** at `a[i-1]`, `b[j-1]` |
| On mismatch | `max(dp[i-1][j], dp[i][j-1])` | `0` |
| Where the answer is | `dp[m][n]` | Maximum over the whole table |
| Time / space | O(mn) / O(mn), or O(min(m, n)) for length only | O(mn) / O(mn), or O(min(m, n)) for length only |
The Recurrence
For substrings, a cell only cares about the run that ends at its two characters. If a[i-1] == b[j-1], the run extends the one on the diagonal, so dp[i][j] = dp[i-1][j-1] + 1. If the characters differ, no run can end here, so dp[i][j] = 0.
LCS takes max of its neighbours on a mismatch. That step lets a subsequence skip a character in either string. Substrings cannot skip anything, so the value resets.
Implementation
Because the values reset, the best run can end anywhere. Track the maximum while filling the table, and store where it ends so you can slice it out. You don't need a traceback.
def longest_common_substring(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
best, end = 0, 0
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:
best = dp[i][j]
end = i
return a[end - best:end]
result = longest_common_substring("ABCBDAB", "BDCABA")
print(result, len(result)) # AB 2The strict > keeps the first maximal run found in row-major order, so the function returns "AB" rather than "BD". Change the comparison to >= and it returns the last maximal run instead.
Each cell reads only its diagonal neighbour, so you can keep just two rows here as well. Unlike LCS, you still recover the actual substring in reduced space, because best and end are enough to slice it from a. For very large inputs, suffix automata or generalized suffix trees solve the problem in linear time.
Exercise
For a = "XYZABC" and b = "ABCXYZ", what are the longest common substring length and the LCS length? Explain why they are equal here.
Show answer
Both are 3. The longest common substrings are "XYZ" and "ABC". The LCS also has length 3, because any common subsequence must take its characters entirely from "XYZ" or entirely from "ABC": the two blocks appear in opposite orders in the two strings. Here the best subsequence happens to be contiguous.
Exercise
In the substring table for "ABCBDAB" and "BDCABA", what is dp[7][6], and why is it not the answer?
Show answer
a[6] is 'B' and b[5] is 'A'. They differ, so dp[7][6] = 0. That cell only describes a run ending at both final characters. The answer, 2, is the largest value anywhere in the table.