What is the Longest Common Subsequence (LCS)?
Answer
The Longest Common Subsequence (LCS) problem finds the longest sequence that appears in the same relative order in both strings, but not necessarily consecutively. Subsequence vs Substring: subsequence elements don't need to be contiguous; substring elements must be. Example: LCS("ABCBDAB", "BDCAB") = "BCAB" or "BDAB", length 4. DP recurrence: let dp[i][j] = LCS length of s1[0..i-1] and s2[0..j-1]: if s1[i-1] == s2[j-1]: dp[i][j] = dp[i-1][j-1] + 1; else: dp[i][j] = max(dp[i-1][j], dp[i][j-1]). Base: dp[0][j] = dp[i][0] = 0. Time: O(m×n). Space: O(m×n), optimized to O(min(m,n)) using two rows. Reconstruct the actual LCS by backtracking through the dp table. Applications: (1) Git diff — find common lines between two versions of a file; (2) Spell checking — edit distance variant; (3) Bioinformatics — DNA/protein sequence alignment; (4) File comparison tools. Related: Longest Common Substring (contiguous), Edit Distance (Levenshtein distance), Diff algorithm. LCS is a classic 2D DP problem that appears frequently in interviews and demonstrates the power of DP for string comparison problems.