Sub topic 8
Recovering the Subsequence by Traceback
The bottom-up table from the previous chapter gives you the length of the longest common subsequence in its bottom-right cell. Most real uses need the subsequence itself: a diff tool has to know which lines match. This chapter shows how to walk backward through the filled table to recover one LCS. It also explains why the walk is correct and covers the mistakes that most often break it.
This chapter assumes you can already build the (m+1) × (n+1) table dp, where dp[i][j] is the LCS length of the prefixes a[:i] and b[:j]. It also assumes you are comfortable with the off-by-one convention in which cell (i, j) refers to the characters a[i-1] and b[j-1].
The Idea: Replay the Recurrence in Reverse
Each cell in the table was filled by one of three choices:
- Diagonal. The characters
a[i-1]andb[j-1]matched, sodp[i][j] = dp[i-1][j-1] + 1. - Up. The characters differed, and dropping
a[i-1]gave the best value,dp[i-1][j]. - Left. The characters differed, and dropping
b[j-1]gave the best value,dp[i][j-1].
Traceback starts at (m, n) and asks at each cell which choice could have produced its value. A diagonal move means the matched character belongs to the LCS, so you record it. An up or left move discards one character and records nothing. The walk stops when either index reaches 0, because an empty prefix shares nothing with anything.
The characters come out last-to-first, so you reverse them at the end.
Implementation
The code below splits table construction from traceback, so you can inspect the path the walk takes. The lcs wrapper matches the combined function from the tutorial's plan.
def build_table(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
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])
return dp
def traceback(a, b, dp):
out, path = [], []
i, j = len(a), len(b)
while i > 0 and j > 0:
path.append((i, 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
path.append((i, j))
return "".join(reversed(out)), path
def lcs(a, b):
return traceback(a, b, build_table(a, b))[0]
a, b = "ABCBDAB", "BDCABA"
dp = build_table(a, b)
result, path = traceback(a, b, dp)
print(result, len(result)) # BCBA 4
print(path)
# [(7, 6), (6, 6), (5, 5), (4, 5), (3, 4), (3, 3), (2, 2), (2, 1), (1, 0)]Worked Trace
In the table below, rows are prefixes of a = "ABCBDAB" and columns are prefixes of b = "BDCABA". Cells on the traceback path are shown in brackets.
| a \ b | ∅ | B | D | C | A | B | A |
|---|---|---|---|---|---|---|---|
| ∅ | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| A | [0] | 0 | 0 | 0 | 1 | 1 | 1 |
| B | 0 | [1] | [1] | 1 | 1 | 2 | 2 |
| C | 0 | 1 | 1 | [2] | [2] | 2 | 2 |
| B | 0 | 1 | 1 | 2 | 2 | [3] | 3 |
| D | 0 | 1 | 2 | 2 | 2 | [3] | 3 |
| A | 0 | 1 | 2 | 2 | 3 | 3 | [4] |
| B | 0 | 1 | 2 | 2 | 3 | 4 | [4] |
Step by step:
- At
(7, 6), B ≠ A. Up and left are both 4, and the>=rule picks up. - At
(6, 6), A = A. Record A and move diagonally. - At
(5, 5), D ≠ B. Up is 3 and left is 2, so move up. - At
(4, 5), B = B. Record B and move diagonally. - At
(3, 4), C ≠ A. Up is 1 and left is 2, so move left. - At
(3, 3), C = C. Record C and move diagonally. - At
(2, 2), B ≠ D. Up is 0 and left is 1, so move left. - At
(2, 1), B = B. Record B and move diagonally to(1, 0), where the walk stops.
The recorded characters are A, B, C, B. Reversed, they give BCBA, which has length 4 and matches dp[7][6].
Why the Walk Is Correct
The walk keeps one invariant: when it stands at (i, j), it still needs to collect exactly dp[i][j] characters, and those characters must form an LCS of a[:i] and b[:j].
- On a match, the recurrence guarantees
dp[i-1][j-1] = dp[i][j] - 1. Recording one character and moving diagonally keeps the invariant. - On a mismatch,
dp[i][j]equals the larger of its up and left neighbors. Moving to the larger neighbor keeps the count the same and records nothing.
The walk ends at a cell whose value is 0. By then it has recorded exactly dp[m][n] characters. Each recorded character came from a matching pair (i-1, j-1), and both indices strictly decrease, so the result is a subsequence of both strings.
Common Errors
Testing table values instead of characters
You might try to detect a diagonal step with dp[i][j] == dp[i-1][j-1] + 1. That test is not enough. A mismatched cell can also be exactly one more than its diagonal neighbor when both its up and left neighbors are larger than the diagonal. Following the diagonal in that case records a character that does not match. Always compare a[i-1] == b[j-1].
Moving toward the smaller neighbor
When the characters differ, moving to the smaller of the two neighbors drops below dp[i][j]. The walk then returns a common subsequence that is too short. A typo such as <= in place of >= with the branches unchanged causes exactly this bug.
Index and ordering slips
- Using
a[i]instead ofa[i-1]either shifts every comparison by one position or raises anIndexErrorati = m. - Forgetting to reverse returns the LCS backward.
- Writing the loop condition as
while i > 0 or j > 0makes the code compare againsta[-1]orb[-1]once one index reaches 0. Python's negative indexing hides the bug, so the code does not crash.
The Tie-Breaking Rule Changes the Answer
When up and left are equal, both moves are valid, and each can lead to a different LCS of the same length. The >= rule prefers up. If you change it to > (preferring left on ties), the same table yields BDAB. Both answers are correct. A later chapter looks at how many solutions can exist and how to enumerate them. For now, treat the tie rule as a deliberate choice. If your output must be deterministic, for example in tests or in a diff tool, document the rule you use.
Traceback Cost
Each step decreases i, j, or both, so the walk takes at most m + n steps. Traceback therefore runs in O(m + n) time, which is small next to the O(mn) cost of filling the table. The memory cost is the issue: the full table uses O(mn) space.
Verifying Your Implementation
Hand-checking one example does not prove much, because tie-breaking can hide bugs. A randomized test against a brute-force reference catches the errors listed above. Append this block to the file that defines lcs and run it.
import random
from itertools import combinations
def is_subsequence(s, t):
it = iter(t)
return all(ch in it for ch in s)
def brute_force_lcs_length(a, b):
for k in range(min(len(a), len(b)), -1, -1):
for idx in combinations(range(len(a)), k):
cand = "".join(a[i] for i in idx)
if is_subsequence(cand, b):
return k
return 0
random.seed(1)
for _ in range(500):
a = "".join(random.choices("ABC", k=random.randint(0, 8)))
b = "".join(random.choices("ABC", k=random.randint(0, 8)))
s = lcs(a, b)
assert is_subsequence(s, a) and is_subsequence(s, b), (a, b, s)
assert len(s) == brute_force_lcs_length(a, b), (a, b, s)
print("all checks passed")The test checks two separate properties. The result must be a subsequence of both inputs, and its length must be optimal. A buggy traceback can pass one check and fail the other. Recording a mismatched character breaks the first property. Moving toward the smaller neighbor breaks the second. The small alphabet "ABC" makes matches and ties frequent, which is where traceback bugs show up.
Exercise
Using the table above for "ABCBDAB" and "BDCABA", change the tie rule so that on a mismatch the walk moves up only when dp[i-1][j] > dp[i][j-1], and otherwise moves left. Which LCS does traceback return?
Show answer
BDAB. From (7,6) the tie sends the walk left to (7,5). There B = B, so it records B and moves to (6,4). A = A, so it records A and moves to (5,3). D ≠ C with a tie at 2, so it moves left to (5,2). D = D, so it records D and moves to (4,1). B = B, so it records B and moves to (3,0). The recorded characters are B, A, D, B, which reverse to BDAB.
Exercise
Give a concrete pair of strings for which the test dp[i][j] == dp[i-1][j-1] + 1 wrongly signals a match at the bottom-right cell.
Show answer
a = "AB", b = "BA". Here dp[1][1] = 0 and dp[2][2] = 1, so the test passes. But a[1] = 'B' and b[1] = 'A' do not match. Following the diagonal would record 'B' and then continue from (1,1), and the walk can return a string that is not a subsequence of b. Comparing the characters themselves avoids this.
Exercise
Why does traceback take O(m + n) time while filling the table takes O(mn)?
Show answer
Every traceback step decreases i, j, or both by one, and the walk stops when either reaches 0. That allows at most m + n steps of O(1) work each. Filling the table visits every one of the m × n cells.