What is the Longest Common Subsequence (LCS)?
Why Interviewers Ask This
This question targets practical, hands-on experience with Data Structures & Algorithms. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.
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.
Pro Tip
If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.