Sub topic 8
Recovering the Subsequence by Traceback
This chapter assumes you have built the bottom-up DP table from the previous chapter. In that table, dp[i][j] holds the LCS length of the first i characters of a and the first j characters of b. You should also be comfortable with 0-based and 1-based index shifts in Python.
The table tells you that the LCS of "ABCBDAB" and "BDCABA" has length 4. It does not tell you what the subsequence is. To get the characters themselves, you walk backward through the table and repeat the decisions that produced each cell.
The Idea Behind Traceback
Every cell was filled by one of two rules:
- If
a[i-1] == b[j-1], thendp[i][j] = dp[i-1][j-1] + 1. The matching character belongs to the LCS. - Otherwise,
dp[i][j]copied the larger of the cell above (dp[i-1][j]) and the cell to the left (dp[i][j-1]).
Traceback starts at the bottom-right cell dp[m][n] and works out which rule applied there. A match means you record the character and move diagonally. A mismatch means you step toward whichever neighbor holds the larger value, since that is where the value was copied from. You stop when you reach row 0 or column 0.
The Code
def lcs(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])
out = []
i, j = m, n
while i > 0 and j > 0:
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 "".join(reversed(out))
result = lcs("ABCBDAB", "BDCABA")
print(result, len(result)) # BCBA 4The walk collects characters from last to first, so the list is reversed at the end. Each step decreases i, j, or both, so traceback takes at most m + n steps. That is O(m + n) on top of the O(mn) needed to fill the table.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Comparing `a[i]` with `b[j]` instead of `a[i-1]` with `b[j-1]` | `IndexError` or wrong characters | Row `i` of the table corresponds to character `a[i-1]` |
| Forgetting to reverse `out` | LCS printed backward, e.g. `ABCB` | Reverse once after the loop |
| Moving diagonally on a mismatch | Result shorter than `dp[m][n]` | Move diagonally only when the characters match |
| Using a two-row table | No table left to walk | Traceback needs the full table, or Hirschberg's method (a later chapter) |
The comparison uses >=, which breaks ties by moving up. Changing it to > makes ties move left, and that can return a different subsequence of the same length. The chapter on ties covers this in detail.
Exercise
During traceback you are at a cell where a[i-1] != b[j-1], dp[i-1][j] = 2, and dp[i][j-1] = 3. Which way do you move, and why?
Show answer
Move left (j -= 1). The cell's value was copied from the larger neighbor, which is the left one with value 3. Moving up would lead to a cell that can only produce a subsequence of length 2, so the result would be shorter than the true LCS.
Exercise
Why can't you recover the subsequence from the two-row version of the algorithm?
Show answer
Traceback needs every cell on the path from dp[m][n] back to row 0 or column 0. The two-row version throws away all earlier rows, so the information about which rule filled each cell is gone. Only the final length is left.