Delete Operation for Two Strings - Problem

Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same.

In one step, you can delete exactly one character in either string.

The goal is to find the minimum number of deletions needed so that both strings become identical.

Input & Output

Example 1 — Basic Case
$ Input: word1 = "sea", word2 = "eat"
Output: 2
💡 Note: Delete 's' from word1 and 't' from word2 to make both strings "ea". Total: 2 deletions.
Example 2 — No Common Characters
$ Input: word1 = "abc", word2 = "def"
Output: 6
💡 Note: No common characters, so delete all 3 characters from word1 and all 3 from word2. Total: 6 deletions.
Example 3 — Identical Strings
$ Input: word1 = "hello", word2 = "hello"
Output: 0
💡 Note: Strings are already identical, no deletions needed.

Constraints

  • 1 ≤ word1.length, word2.length ≤ 500
  • word1 and word2 consist of only lowercase English letters

Visualization

Tap to expand
Delete Operation for Two Strings INPUT word1 = "sea" s e a 0 1 2 word2 = "eat" e a t 0 1 2 Input Values: word1 = "sea" (len=3) word2 = "eat" (len=3) ALGORITHM STEPS 1 Find LCS Longest Common Subsequence 2 Build DP Table dp[i][j] = LCS of substrings 3 Get LCS Length LCS("sea","eat") = "ea" = 2 4 Calculate Deletions (len1-LCS) + (len2-LCS) DP Table (LCS values): e a t s 0 0 0 e 1 1 1 a 1 2 2 LCS = 2 (chars: "ea") FINAL RESULT Common Subsequence: "ea" From "sea": s e a DELETE KEEP From "eat": e a t KEEP DELETE Calculation: (3 - 2) + (3 - 2) = 1 + 1 = 2 Output: 2 Key Insight: The minimum deletions = (len(word1) - LCS) + (len(word2) - LCS) = len(word1) + len(word2) - 2 * LCS Characters in LCS are common to both strings and don't need deletion. Delete everything else! TutorialsPoint - Delete Operation for Two Strings | LCS-Based Approach
Asked in
Google 15 Facebook 12 Amazon 8 Microsoft 6
78.5K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen