πΉ Problem
Given two strings:
s1 β convert into β s2
π Find:
- Minimum deletions
- Minimum insertions
π₯ Key Idea (VERY IMPORTANT)
π Use Longest Common Subsequence (LCS)
Let L = LCS(s1, s2)
πΉ Formula
Deletions = n - L
Insertions = m - L
Where:
n = length of s1m = length of s2
π§ Why this works?
- LCS = part already common β no need to change
- Remove extra from
s1β deletions - Add missing for
s2β insertions
πΉ Example
s1 = "heap"
s2 = "pea"
π LCS = "ea" β length = 2
Deletions = 4 - 2 = 2
Insertions = 3 - 2 = 1
πΉ Code (C++)
int lcs(string s1, string s2) {
int n = s1.size(), m = s2.size();
vector<int> prev(m+1, 0), curr(m+1, 0);
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
if(s1[i-1] == s2[j-1])
curr[j] = 1 + prev[j-1];
else
curr[j] = max(prev[j], curr[j-1]);
}
prev = curr;
}
return prev[m];
}
pair<int,int> minInsertDelete(string s1, string s2) {
int n = s1.size(), m = s2.size();
int L = lcs(s1, s2);
int deletions = n - L;
int insertions = m - L;
return {deletions, insertions};
}
πΉ Total Operations
If asked:
Minimum operations = deletions + insertions
= n + m - 2*LCS
πΉ Important Variants
β Only deletions:
n - LCS
β Only insertions:
m - LCS
π₯ Interview Pattern
π If you see:
- βConvert string A β Bβ
- βInsert/Delete operations onlyβ
β‘οΈ Think:
Use LCS
β‘ Quick Summary
L = LCS(s1, s2)
Delete = n - L
Insert = m - L
Total = n + m - 2L
π§ Intuition Shortcut
Keep common part (LCS)
Remove rest from s1
Add rest from s2
If you want next π
I can show:
β
Edit Distance (insert + delete + replace)
β
Print actual operations
β
Hard problems based on this
Just tell me π
Top comments (0)