Full answer
Problem
Given strings a and b, return the length of their longest common subsequence and one such subsequence. A subsequence keeps the order of characters but need not be contiguous.
Example: a = "abcde", b = "ace" gives (3, "ace"). For "ABCBDAB" and "BDCABA" the length is 4 ("BCBA" is one answer; others exist).
Constraints: 0 <= len(a), len(b) <= 1000.
Brute force
Try every subsequence of the shorter string (2^m of them) and check each against the other in O(n): O(n x 2^m). Plain recursion on (i, j) without memoisation is also exponential, because the same pairs are solved many times.
Optimal approach
dphas(m + 1) x (n + 1)cells, with row 0 and column 0 equal to 0 (an empty prefix has LCS 0).- For each
i,j:a[i - 1] == b[j - 1]:dp[i][j] = dp[i - 1][j - 1] + 1.- Otherwise:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]).
- Reconstruct: from
(m, n), on a match add the character and move diagonally; otherwise move towards the larger neighbour. Reverse the collected characters.
Space saving for the length only: keep just the previous and current rows, iterating over the longer string so rows have length min(m, n) + 1.
Why it works
Optimal substructure: if the last characters match, some LCS ends with that character, and the rest is an LCS of the shorter prefixes. If they differ, at least one of them is not in the LCS, so the answer is the better of dropping one or the other. Each cell depends only on cells above and to the left, so filling row by row has all inputs ready. Reconstruction follows the choices that produced each value.
Complexity
O(m x n) time. O(m x n) space for the full table with reconstruction; O(min(m, n)) for length only. Hirschberg's algorithm reconstructs in linear space with divide and conquer.
Code
def lcs(a, b):
"""Length and one longest common subsequence of a and b. O(m * n) time and space."""
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)] # dp[i][j] = LCS length of a[:i], b[:j]
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
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
out, i, j = [], m, n # walk back to rebuild one answer
while i and j:
if a[i - 1] == b[j - 1]:
out.append(a[i - 1])
i -= 1
j -= 1
elif dp[i - 1][j] >= dp[i][j - 1]:
i -= 1
else:
j -= 1
return dp[m][n], "".join(reversed(out))
def lcs_length(a, b):
"""Length only, with two rows: O(m * n) time, O(min(m, n)) space."""
if len(b) > len(a):
a, b = b, a
prev = [0] * (len(b) + 1)
for x in a:
cur = [0]
for j, y in enumerate(b, 1):
cur.append(prev[j - 1] + 1 if x == y else max(prev[j], cur[j - 1]))
prev = cur
return prev[-1]
def is_subsequence(s, t):
it = iter(t)
return all(ch in it for ch in s)
if __name__ == "__main__":
length, seq = lcs("ABCBDAB", "BDCABA")
assert length == 4 and is_subsequence(seq, "ABCBDAB") and is_subsequence(seq, "BDCABA")
assert lcs("abcde", "ace") == (3, "ace")
assert lcs("abc", "def") == (0, "")
assert lcs("", "abc") == (0, "")
assert lcs("same", "same") == (4, "same")
for a, b in [("ABCBDAB", "BDCABA"), ("abcde", "ace"), ("", "x"), ("AGGTAB", "GXTXAYB")]:
assert lcs_length(a, b) == lcs(a, b)[0]
assert lcs_length("AGGTAB", "GXTXAYB") == 4
print("all tests passed")Save as a50_lcs.py and run python3 a50_lcs.py. It prints all tests passed (Python 3.13.5).
Edge cases
Either string empty gives (0, ""). No common characters. Identical strings return the whole string. When several LCSs exist, tie-breaking in the walk-back decides which one is returned; the test checks validity with is_subsequence rather than one fixed answer.
Pattern
Two-sequence DP on prefixes. Related: edit distance, shortest common supersequence, diff tools (which find an LCS of lines), and DNA sequence alignment.
def lcs(a, b):
"""Length and one longest common subsequence of a and b. O(m * n) time and space."""
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)] # dp[i][j] = LCS length of a[:i], b[:j]
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
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
out, i, j = [], m, n # walk back to rebuild one answer
while i and j:
if a[i - 1] == b[j - 1]:
out.append(a[i - 1])
i -= 1
j -= 1
elif dp[i - 1][j] >= dp[i][j - 1]:
i -= 1
else:
j -= 1
return dp[m][n], "".join(reversed(out))
def lcs_length(a, b):
"""Length only, with two rows: O(m * n) time, O(min(m, n)) space."""
if len(b) > len(a):
a, b = b, a
prev = [0] * (len(b) + 1)
for x in a:
cur = [0]
for j, y in enumerate(b, 1):
cur.append(prev[j - 1] + 1 if x == y else max(prev[j], cur[j - 1]))
prev = cur
return prev[-1]
def is_subsequence(s, t):
it = iter(t)
return all(ch in it for ch in s)
if __name__ == "__main__":
length, seq = lcs("ABCBDAB", "BDCABA")
assert length == 4 and is_subsequence(seq, "ABCBDAB") and is_subsequence(seq, "BDCABA")
assert lcs("abcde", "ace") == (3, "ace")
assert lcs("abc", "def") == (0, "")
assert lcs("", "abc") == (0, "")
assert lcs("same", "same") == (4, "same")
for a, b in [("ABCBDAB", "BDCABA"), ("abcde", "ace"), ("", "x"), ("AGGTAB", "GXTXAYB")]:
assert lcs_length(a, b) == lcs(a, b)[0]
assert lcs_length("AGGTAB", "GXTXAYB") == 4
print("all tests passed")Full table with reconstruction, a two-row length-only version and an is_subsequence helper used to check the result.
Complexity
Time: O(m * n). Space: O(m * n) with reconstruction; O(min(m, n)) for the length only. Hirschberg's algorithm reconstructs an LCS in linear space.
By level
Fresher: Defines dp on prefixes, writes the recurrence and fills a small table for "abcde" and "ace". Should test an empty string.
Mid: Reconstructs an LCS, reduces space to two rows and explains why several answers can exist. Tests strings with no common characters.
Senior: Relates LCS to edit distance and diff tools, discusses Hirschberg's linear-space method and bit-parallel speedups for long inputs. Can explain why plain recursion without memoisation is exponential.
Key points
- dp[i][j] is the LCS of the prefixes a[:i] and b[:j]
- Match: diagonal plus 1; otherwise max of up and left
- Row 0 and column 0 are 0
- Walk back from the corner to rebuild
- Two rows suffice for the length
Common mistakes
- Confusing subsequence with substring
- Off-by-one between dp indices and string indices
- Plain recursion without memoisation
- Expecting one unique LCS when several exist
Follow-ups
- How does edit distance differ from LCS?
- How do diff tools use LCS?
- How would you find the longest common substring instead?
Tips
- Define the state in words first
- Fill a small table on the board
- Mention the space optimisation
Evaluation rubric
- Correct recurrence and base cases
- Correct reconstruction
- Correct complexity
- Handles empty strings and ties