Minimum Edit Distance Between Two Strings
The Minimum Edit Distance problem asks for the fewest number of single-character edits (insertions, deletions, or substitutions) required to change one word into the other. This is a fundamental problem in computer science with applications in spell checking, DNA sequencing, and plagiarism detection.
Problem Description
Given two strings, str1 and str2, your task is to find the minimum number of operations needed to transform str1 into str2. The allowed operations are:
- Insertion: Insert a character into
str1. - Deletion: Delete a character from
str1. - Substitution: Replace a character in
str1with another character.
You should return the count of these operations.
Examples
Example 1:
Input:
str1 = "horse"
str2 = "ros"
Output: 3
Explanation:
- Substitute 'h' with 'r' ("rorse")
- Delete 'r' ("rose")
- Delete 'e' ("ros")
Example 2:
Input:
str1 = "intention"
str2 = "execution"
Output: 5
Explanation:
- Delete 'i' ("ntention")
- Replace 'n' with 'e' ("etention")
- Replace 't' with 'x' ("exention")
- Replace 'n' with 'c' ("execntion")
- Insert 'u' ("execution")
Example 3:
Input:
str1 = ""
str2 = "abc"
Output: 3
Explanation: To transform an empty string into "abc", we need to insert all three characters.
Constraints
- The lengths of
str1andstr2are between 0 and 500, inclusive. str1andstr2consist of lowercase English letters.- The solution should aim for an efficient time complexity.
Notes
This problem can be approached using dynamic programming. Consider how the edit distance between prefixes of the strings relates to the overall problem. Think about the base cases for empty strings and single-character strings.