Longest Common Subsequence (LCS)
Compare pairs of prefixes. At matching characters, extend the result for the two shorter prefixes.
Core Intuition & How It Works
Longest Common Subsequence (LCS) measures the longest sequence appearing in the same relative order in two strings. A 2D DP table matches characters diagonally (1 + dp[i-1][j-1]) or takes the better skip (max of top or left).
In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.
Time & Space Complexity
| Metric | Complexity |
|---|---|
| Time Complexity | O(m × n) |
| Space Complexity | O(m × n) or O(min(m, n)) |
| Topic Chapter | Chapter 13: Dynamic Programming |
| Difficulty Level | Advanced |
Key Pattern to Recognize
Pad the DP table with an extra row and column of zeros at index 0 so empty-prefix base cases require no conditionals.
Common Pitfalls & Edge Cases
Confusing subsequence (non-contiguous) with substring (contiguous, which resets to 0 on mismatch).
Real-World & Technical Interview Applications
Git diff / patch generation, DNA/protein sequence alignment, and plagiarism detection.