Longest Common Subsequence
Fill for the optimal length, then trace for an actual subsequence
Preserve order without requiring adjacency
A subsequence keeps the original character order but may skip characters. For prefixes of strings X and Y, let dp[i][j] be their longest common subsequence length. Empty prefixes form the zero row and column.
Match diagonally or discard one character
When X[i - 1] === Y[j - 1], append that shared character to the best solution for the shorter prefixes, giving the top-left value plus 1. Otherwise one current character must be skipped, so keep the larger value from the up and left cells.
After the table is full, the player traces backward from the bottom-right cell. A character match moves diagonally and records that character; a mismatch follows a neighboring cell that preserves the optimal length. The highlighted path reconstructs ACD.
| ∅ | A | C | D | F | |
|---|---|---|---|---|---|
| ∅ | 0 | 0 | 0 | 0 | 0 |
| A | 0 | ||||
| B | 0 | ||||
| C | 0 | ||||
| D | 0 |
Initialize the empty-prefix row and column to 0.
Value first, witness second
The table takes O(mn) time and space. This two-phase pattern appears throughout dynamic programming: first compute the optimal value, then follow stored choices to recover a concrete solution.
Contrast this maximum-length recurrence with Edit Distance, or continue to a one-dimensional subsequence DP in Longest Increasing Subsequence.