Introduction
The Longest Common Subsequence (LCS) problem is one of the most important String Dynamic Programming interview questions.
A subsequence is formed by deleting zero or more characters without changing the relative order of the remaining characters.
Goal:
Find the length of the longest subsequence common to both strings.Example
text1 = "abcde"
text2 = "ace"Output = 3
Explanation:
Common Subsequence = "ace"Length = 3Constraints
1 <= text1.length <= 10001 <= text2.length <= 1000Key Observation
If characters match:
dp[i][j] = 1 + dp[i-1][j-1] If characters do not match:
dp[i][j] = max(dp[i-1][j], dp[i][j-1]) This forms the DP recurrence.
Approach 1 : Memoization
Explanation
Use recursion and store previously computed results.
Steps:
- Compare characters.
- If equal, include the character.
- If different, try both possibilities.
- Store results.
- Reuse answers.
Approach 2 : Tabulation
Explanation
Build a DP table from smaller prefixes.
Base Case:
Empty string has LCS length 0. Transition:
If text1[i-1] == text2[j-1]
dp[i][j] = 1 + dp[i-1][j-1]
Elsedp[i][j] = max(dp[i-1][j], dp[i][j-1])
Dry Run
Input:
text1 = "abcde"text2 = "ace"DP Table:
a c e
0 0 0 0
a 0 1 1 1
b 0 1 1 1
c 0 1 2 2
d 0 1 2 2e 0 1 2 3
Answer:
3 Approach 3 : Space Optimized DP
Explanation
Instead of storing the entire matrix:
m × n Store only the previous row.
This reduces memory usage.
Practice
Complexity Analysis
Memoization
Time Complexity: O(m × n)
Space Complexity: O(m × n)
Tabulation Time Complexity: O(m × n)
Space Complexity: O(m × n)
Space Optimized DP
Time Complexity: O(m × n)Space Complexity: O(n)
Why This Problem is Important
- String Dynamic Programming
- 2D DP Tables
- Character Matching
- State Transitions
- Space Optimization
Common Beginner Mistakes
- Confusing substring with subsequence
- Wrong DP dimensions
- Incorrect indexing
- Missing base cases
- Using greedy approach
Interview Tip
Always explain:
If characters match:Take diagonal + 1
Else: Take maximum of top and left.
This pattern appears in many advanced string DP problems.
Related Questions
- Edit Distance
- Longest Palindromic Subsequence
- Distinct Subsequences
- Shortest Common Supersequence
- Minimum Insertions to Make Palindrome
Final Takeaway
Longest Common Subsequence is one of the most important Dynamic Programming problems.
It teaches:
- String DP
- 2D DP
- Character matching
- State transitions
- Space optimization
Mastering LCS makes advanced string-based Dynamic Programming problems significantly easier to solve.