Minimum insertions or deletions to convert string A to B
HardEverything outside the LCS must change
Problem
Return the minimum insertions and deletions to turn string a into string b.
Keep the common subsequence; delete the rest of A and insert the rest of B.
The idea
Characters in the longest common subsequence are shared and stay put. The rest of a must be deleted and the rest of b inserted, so the total is (m - lcs) + (n - lcs).
The trick
- Deletions = m - lcs, insertions = n - lcs.
- One LCS computation answers both.
·
∅
A
C
∅
0
0
0
A
0
0
0
B
0
0
0
C
0
0
0
Step 1 of 8. LCS grid for "ABC" and "AC". Match → diagonal + 1, else the best of up/left.
1/8
Optimal
timeO(n·m)spaceO(n·m)
Match extends the diagonal.
1for (let i = 1; i <= n; i++)2 for (let j = 1; j <= m; j++)3 dp[i][j] = a[i-1] === b[j-1]4 ? dp[i-1][j-1] + 15 : Math.max(dp[i-1][j], dp[i][j-1]);Input
- grid
- 5 × 4
Memory
- at
- —
- cells marked
- 0
Output
- LCS
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- a = "heap", b = "pea"
- Output:
- 3
- Explanation:
- Delete 2 and insert 1 → 3 operations.
Example 2
- Input:
- a = "abc", b = "abc"
- Output:
- 0
- Explanation:
- Identical → 0.
Example 3
- Input:
- a = "abcd", b = "anc"
- Output:
- 3
- Explanation:
- 3 edits via their common subsequence.
Practice this problem:LeetCode(opens in a new tab)Search GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.