Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2.
You have the following three operations permitted on a word:
Example 1:
Input: word1 = "horse", word2 = "ros" Output: 3 Explanation: horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e')
Example 2:
Input: word1 = "intention", word2 = "execution" Output: 5 Explanation: intention -> inention (remove 't') inention -> enention (replace 'i' with 'e') enention -> exention (replace 'n' with 'x') exention -> exection (replace 'n' with 'c') exection -> execution (insert 'u')
Constraints:
0 <= word1.length, word2.length <= 500word1 and word2 consist of lowercase English letters.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have two words and you want to turn the first one into the second one by making as few changes as possible. The brute force approach tries every single combination of insertions, deletions, and replacements until you find the exact path that gets you there with the fewest steps.
Here's how the algorithm would work step-by-step:
def minDistance(word1: str, word2: str) -> int:
def compute_edit_distance(index_word_one, index_word_two):
# Base cases handle exhaustion of either word by returning remaining required operations
if index_word_one == len(word1):
return len(word2) - index_word_two
if index_word_two == len(word2):
return len(word1) - index_word_one
# Matching characters allow us to progress without incurring any additional operation cost
if word1[index_word_one] == word2[index_word_two]:
return compute_edit_distance(index_word_one + 1, index_word_two + 1)
# Mismatches force us to evaluate insertion, deletion, and replacement paths exhaustively
insert_operation = compute_edit_distance(index_word_one, index_word_two + 1)
delete_operation = compute_edit_distance(index_word_one + 1, index_word_two)
replace_operation = compute_edit_distance(index_word_one + 1, index_word_two + 1)
# We select the minimum path cost among our three choices and add one for the current step
return 1 + min(insert_operation, delete_operation, replace_operation)
return compute_edit_distance(0, 0)Instead of blindly trying every single way to transform one word into another, the optimal approach breaks the puzzle down into smaller, overlapping pieces. By comparing the words letter by letter from the end, we can figure out the cheapest way to fix mismatches and save those answers so we never have to solve the same mini-puzzle twice.
Here's how the algorithm would work step-by-step:
def min_distance(source_word: str, target_word: str) -> int:
source_length = len(source_word)
target_length = len(target_word)
distance_grid = [[0] * (target_length + 1) for _ in range(source_length + 1)]
for row_index in range(source_length + 1):
distance_grid[row_index][0] = row_index
for col_index in range(target_length + 1):
distance_grid[0][col_index] = col_index
# Subproblems are solved iteratively from the end of the strings to the beginning.
for source_index in range(1, source_length + 1):
for target_index in range(1, target_length + 1):
if source_word[source_index - 1] == target_word[target_index - 1]:
distance_grid[source_index][target_index] = distance_grid[source_index - 1][target_index - 1]
else:
# We evaluate the minimum cost among insertion, deletion, and replacement operations.
insertion_cost = distance_grid[source_index][target_index - 1]
deletion_cost = distance_grid[source_index - 1][target_index]
replacement_cost = distance_grid[source_index - 1][target_index - 1]
distance_grid[source_index][target_index] = 1 + min(insertion_cost, deletion_cost, replacement_cost)
# The bottom-right cell contains the absolute minimum operations required for the full words.
return distance_grid[source_length][target_length]| Case | How to Handle |
|---|---|
| One or both strings are empty | The dynamic programming table initialization naturally handles this by returning the length of the non-empty string. |
| Both strings are identical | The algorithm will compute a distance of zero because no characters need modification. |
| Strings have no characters in common | The cost will equal the maximum length of the two strings through a series of deletions and insertions. |
| One string is completely contained within the other | The solution correctly calculates the difference in lengths as the exact number of required insertions or deletions. |
| Maximum allowed string lengths up to constraints | Space optimization reduces the O(m * n) space complexity down to O(min(m, n)) to prevent memory limit excesses. |
| Strings containing entirely distinct characters | The transition costs will accumulate purely through replacements or deletions followed by insertions up to the combined length. |
| Strings with alternating or repetitive characters | The dynamic programming state transitions properly evaluate all combinations of shifts to find the global minimum. |