MediumStringDynamic Programming

Edit Distance

LeetCode
1 approach, code in all languages

You are given two strings, word1 and word2. In a single operation you may insert one character, delete one character, or replace one character.

Return the minimum number of operations required to transform word1 into word2.

Example 1

Input: word1 = "horse", word2 = "ros"

Output: 3

Replace 'h' with 'r' to get rorse, delete 'r' to get rose, then delete 'e' to get ros. Three operations is the minimum.

Example 2

Input: word1 = "intention", word2 = "execution"

Output: 5

A minimal sequence uses one replace and several inserts and deletes to align the two words in five total edits.

Constraints

  • 0 <= word1.length, word2.length <= 500
  • word1 and word2 consist of lowercase English letters.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now