Overview
Populating a DP table tells you the length of the optimal solution. Tracing backward through that table tells you the *elements* of that optimal solution.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
After populating the LCS DP table, learn how to reconstruct the actual string instead of just returning the max length.
Populating a DP table tells you the length of the optimal solution. Tracing backward through that table tells you the *elements* of that optimal solution.
You always start your traceback from the final computed answer, which is at the bottom-right corner of the DP matrix: `dp[m][n]`.
If characters match, that character is part of the LCS. Prepend it to the result and move diagonally UP-LEFT (`i-1, j-1`).
If characters don't match, we know the LCS must have come from either the cell ABOVE us or to the LEFT of us. We simply move to whichever has the larger value.
| S1 \ S2 | "" | a | c | e |
|---|---|---|---|---|
| "" | 0 | 0 | 0 | 0 |
| a | 0 | 1 | 1 | 1 |
| b | 0 | 1 | 1 | 1 |
| c | 0 | 1 | 2 | 2 |
| d | 0 | 1 | 2 | 2 |
| e | 0 | 1 | 2 | 3 |