AAlgoLoopSpaced repetition for LeetCode
MEDIUMDynamic ProgrammingLeetCode ↗

Delete Operation for Two Strings

The key idea

The characters you never delete must form a common subsequence of both words, so the fewest deletions keep the longest common subsequence (LCS) and remove everything else: answer = m + n - 2 * LCS(word1, word2).

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.

Constraints

Examples

Input: word1 = "sea", word2 = "eat" Output: 2
Input: word1 = "leetcode", word2 = "etco" Output: 4
Input: word1 = "abcde", word2 = "ace" Output: 2

Complexity

Time: O(m*n) Space: O(m*n)

See the full solution

410310
Step-by-step visualization
Start free →

More Dynamic Programming problems