Longest Common Subsequence
A subsequence preserves order but need not be contiguous. Given sequences and , the LCS problem asks for a maximum-length sequence that is a subsequence of both.
Let be the LCS length of prefixes and :
Empty-prefix rows and columns are zero.
def lcs_length(left: str, right: str) -> int:
previous = [0] * (len(right) + 1)
for left_item in left:
current = [0]
for j, right_item in enumerate(right, start=1):
if left_item == right_item:
current.append(previous[j - 1] + 1)
else:
current.append(max(previous[j], current[-1]))
previous = current
return previous[-1]
Cost and output
- Full table: time and space.
- Length only: time and space after choosing the shorter sequence as the row width.
- Reconstructing an LCS requires retained choices, a full table, or a more specialized divide-and-conquer reconstruction.
The longest common substring is a different problem because matching symbols must be contiguous.