oneby7

2-D Dynamic Programming Two strings

567. Delete Operation for Two Strings

Medium

You are given two strings, word1 and word2. In one step you delete one character from either string.

Return the fewest steps that make the two strings equal. Deleting every character leaves an empty string, and two empty strings are equal, so there is always an answer.

Example 1

Input: word1 = "spare", word2 = "pears"

Output: 4

Explanation: Delete the s and the e from "spare", and the e and the s from "pears". Both strings become "par".

Example 2

Input: word1 = "cat", word2 = "dog"

Output: 6

Explanation: The strings share no letter, so every letter goes, and both end up empty.

Example 3

Input: word1 = "sun", word2 = "sunday"

Output: 3

Explanation: Delete d, a and y from "sunday". Nothing needs to be deleted from "sun".

Check your understanding

Work out the answer for this input before you write any code.

word1 = "tide", word2 = "diet"

Constraints

  • 1 ≤ word1.length, word2.length ≤ 3000
  • word1 and word2 hold only lowercase English letters.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.