2-D Dynamic Programming Two strings

560. Edit Distance

Medium 147 DSA Sheet

You are given two words, word1 and word2. Return the fewest operations that turn word1 into word2.

Each operation changes one letter, in one of three ways:

  • Insert a letter at any position.
  • Delete a letter.
  • Replace a letter with a different letter.

Either word can be empty. Turning a word into itself takes no operations.

Example 1

Input: word1 = "brand", word2 = "hands"

Output: 3

Explanation: Delete the r to get "band", replace the b with h to get "hand", and insert an s at the end.

Example 2

Input: word1 = "", word2 = "sky"

Output: 3

Explanation: An empty word becomes "sky" by inserting its three letters.

Example 3

Input: word1 = "winter", word2 = "writer"

Output: 2

Explanation: Insert an r after the w to get "wrinter", then delete the n.

Check your understanding

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

word1 = "below", word2 = "elbow"

Constraints

  • 0 ≤ word1.length, word2.length ≤ 1000
  • 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

Sign in to oneby7

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

New here? This creates your account too.