How longest common subsequence works
dp[i][j] is the length of the LCS of the first i characters of a and the first j characters of b. If a[i − 1] equals b[j − 1], that character extends the best answer without either of them: dp[i − 1][j − 1] + 1. Otherwise at least one of the two characters is not in the answer, so take the larger of dp[i − 1][j] and dp[i][j − 1].
The example compares "ABCBDAB" and "BDCABA". Their longest common subsequence has length 4 — "BCBA" is one of them.
What to watch for when it runs
- A match reads the cell diagonally up and to the left; a mismatch reads the cell above or to the left.
- The grid has an extra row and column of zeros for the empty prefixes.
- The bottom-right cell is the answer.
Time and space complexity
- Time
- O(m × n)
- Space
- O(m × n)
m and n are the two string lengths. Keeping only two rows brings the memory down to O(n) if you only need the length.