v9.1.1
Menu

Edit Distance

hardFREEDynamic ProgrammingDSA for AI Engineers

Given two strings, return the minimum number of operations (insert, delete, replace) to convert one to the other.

Example

Input
horse
ros
Output
3
Reasoning
  • The input strings are "horse" and "ros", and we need to find the minimum number of operations to convert "horse" to "ros".
  • We start by comparing the two strings: "horse" has 5 characters and "ros" has 3 characters, so we need to delete 2 characters from "horse".
  • To convert "horse" to "ros", we can delete "h" and "e", and replace "o" is not needed as it is present in both, but we need to replace the other characters: the resulting operations are 11 replacement (for "r" to match) and 22 deletions (for "h" and "e"), totaling 33 operations.
  • The final output is 33, which is the minimum number of operations required to convert "horse" to "ros".

Constraints

  • 0 <= len(word1), len(word2) <= 500
  • Strings consist of lowercase English letters

Learn this in

More from DSA for AI Engineers

solution.py

Test results

Sign in to run your code against the test cases.