What is the Longest Common Subsequence problem?
The Longest Common Subsequence (LCS) of two strings is the longest sequence of characters that appears in both strings in the same relative order, but not necessarily contiguously. For example, the LCS of "ABCBDAB" and "BDCABA" is "BCBA", with length 4.
LCS is solved with a 2D DP table where dp[i][j] represents the length of the LCS between the first i characters of string one and the first j characters of string two. Just like the Knapsack Problem, each cell is built from previously solved subproblems, avoiding the exponential cost of checking every possible subsequence.
Time & Space Complexity
- Brute ForceO(2^n)
- DP TimeO(n · m)
- DP SpaceO(n · m)
- Optimized SpaceO(min(n, m))
* n and m are the lengths of the two input strings.
Real-World Use Cases
- ✓Diff Tools & Version ControlTools like Git use LCS-based algorithms to compute differences between file versions.
- ✓BioinformaticsComparing DNA, RNA, or protein sequences to find shared genetic patterns.
- ✓Plagiarism DetectionMeasuring textual similarity between documents.