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: Make "sea" and "eat" IdenticalInitial Stringsword1: "sea"word2: "eat"Find LCSCommon: "ea"Length: 2Delete from word1Remove: "s"Keep: "ea"Delete from word2Remove: "t"Keep: "ea"ResultBoth strings: "ea"Total deletions: 2Formula: len(word1) + len(word2) - 2 × LCS_length3 + 3 - 2 × 2 = 2 deletions
Understanding the Visualization
1
Input Strings
Two strings that need to become identical
2
Find Common Parts
Identify longest common subsequence to keep
3
Calculate Deletions
Delete all characters not in common subsequence
Key Takeaway
🎯 Key Insight: Find the longest common subsequence and delete everything else - this gives the minimum number of deletions needed.
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