Forem

Dolly Sharma
Dolly Sharma

Posted on

πŸ“˜ Minimum Insertions and Deletions to Convert String A -B

πŸ”Ή Problem

Given two strings:

s1 β†’ convert into β†’ s2
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Find:

  • Minimum deletions
  • Minimum insertions

πŸ”₯ Key Idea (VERY IMPORTANT)

πŸ‘‰ Use Longest Common Subsequence (LCS)

Let L = LCS(s1, s2)
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Formula

Deletions = n - L
Insertions = m - L
Enter fullscreen mode Exit fullscreen mode

Where:

  • n = length of s1
  • m = 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"
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ LCS = "ea" β†’ length = 2

Deletions = 4 - 2 = 2
Insertions = 3 - 2 = 1
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 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};
}
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Total Operations

If asked:

Minimum operations = deletions + insertions
                  = n + m - 2*LCS
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Important Variants

βœ… Only deletions:

n - LCS
Enter fullscreen mode Exit fullscreen mode

βœ… Only insertions:

m - LCS
Enter fullscreen mode Exit fullscreen mode

πŸ”₯ Interview Pattern

πŸ‘‰ If you see:

  • β€œConvert string A β†’ B”
  • β€œInsert/Delete operations only”

➑️ Think:

Use LCS
Enter fullscreen mode Exit fullscreen mode

⚑ Quick Summary

L = LCS(s1, s2)

Delete = n - L
Insert = m - L
Total = n + m - 2L
Enter fullscreen mode Exit fullscreen mode

🧠 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)