Taro Logo

Edit Distance

#38 Most AskedMedium
0 views
Topics:
StringsDynamic Programming

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:

  • Insert a character
  • Delete a character
  • Replace a character

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 <= 500
  • word1 and word2 consist of lowercase English letters.

Solution


Clarifying Questions

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:

  1. What is the maximum expected length of word1 and word2, and should we be concerned about memory limits for very large strings?
  2. Can either word1 or word2 be empty strings, and if so, is the expected answer simply the length of the non-empty string?
  3. Are the input strings restricted to lowercase English letters, or can they contain uppercase letters, numbers, or special unicode characters?
  4. Are all three operations (insert, delete, replace) weighted equally with a cost of 1, or could different operations have varying costs?
  5. If multiple sequences of operations yield the exact same minimum edit distance, do you have a preference for which operations are performed, or do you only care about the final minimum count?

Brute Force Solution

Approach

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:

  1. Begin at the very start of both words and compare the letters side by side.
  2. If the letters match, simply move forward to compare the next letters without making any changes.
  3. If the letters do not match, imagine you have three choices to fix the mismatch.
  4. First, try inserting a matching letter and see what happens down that path.
  5. Second, try deleting the current letter from the starting word and continue.
  6. Third, try replacing the mismatch with the correct letter and move ahead.
  7. Explore every single branch of these choices all the way to the end of both words.
  8. Count the total number of changes made along every single possible path.
  9. Compare the change counts from all the finished paths and pick the one with the smallest total.

Code Implementation

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)

Big(O) Analysis

Time Complexity
O(m * n) – The time complexity is driven by comparing every possible prefix of the first word of length m against every possible prefix of the second word of length n. We can solve this efficiently using a two-dimensional grid of subproblems, where each cell takes constant time to compute by looking at its neighbors. This requires filling a table of size m by n, leading to approximately m * n operations in total. Simplifying this product yields a final Big O time complexity of O(m * n).
Space Complexity
O(m * n) – To implement the dynamic programming approach described, we allocate a two-dimensional auxiliary table of size (m + 1) by (n + 1) to store the intermediate edit distances between prefixes of the two words. As the lengths of the words, which we can generalize as N, grow, this 2D grid requires memory scaling quadratically with the input size. Additionally, if using a recursive memoization strategy, the recursion call stack would grow to a maximum depth proportional to the sum of both word lengths. Therefore, the total extra memory is dominated by this 2D table, resulting in a space complexity of O(N * M) or O(N squared) when both words are of similar length.

Optimal Solution

Approach

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:

  1. Imagine lining up the two words side by side and comparing them starting from their final letters and moving backward toward the beginning.
  2. Whenever the ending letters happen to match, you can simply ignore that pair and instantly move on to the next letters because no changes are needed.
  3. Whenever the letters do not match, you have three distinct choices to fix the mismatch: you can insert a matching letter, delete the offending letter, or replace it with the correct one.
  4. To figure out which of those three choices is best, look at the cost of fixing the remaining parts of the words for each choice and pick the path that requires the fewest total steps.
  5. As you figure out the best solution for each pairing of word segments, write down the answer in a mental grid so you can remember it later.
  6. Continue this process step by step, using your previously saved answers to build up the solution until you reach the very beginning of both words.
  7. By the time you compare the starting letters, your final saved answer will reveal the absolute minimum number of changes required to transform the first word into the second.

Code Implementation

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]

Big(O) Analysis

Time Complexity
O(m * n) – The time complexity is driven by filling out a two-dimensional grid where each cell represents the subproblem of finding the edit distance between a prefix of the first word and a prefix of the second word. With m representing the length of the first word and n representing the length of the second word, the algorithm uses nested loops to iterate through every possible pair of prefixes. Inside these loops, constant-time comparisons and choices are made using previously saved answers. This results in approximately m times n operations to fill the grid, which simplifies to the final Big O notation.
Space Complexity
O(m * n) – To implement the mental grid mentioned in the explanation, we utilize a 2D auxiliary array or table of size (m + 1) by (n + 1), where m and n are the lengths of the two input words. This grid stores the intermediate results of previously solved mini-puzzles to avoid redundant calculations. As the lengths of the words increase, the memory required for this grid grows proportionally to the product of their sizes. Therefore, the total extra memory simplifies to Big O of m times n, or O(N * M) depending on the variable notation.

Edge Cases

One or both strings are empty
How to Handle:
The dynamic programming table initialization naturally handles this by returning the length of the non-empty string.
Both strings are identical
How to Handle:
The algorithm will compute a distance of zero because no characters need modification.
Strings have no characters in common
How to Handle:
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
How to Handle:
The solution correctly calculates the difference in lengths as the exact number of required insertions or deletions.
Maximum allowed string lengths up to constraints
How to Handle:
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
How to Handle:
The transition costs will accumulate purely through replacements or deletions followed by insertions up to the combined length.
Strings with alternating or repetitive characters
How to Handle:
The dynamic programming state transitions properly evaluate all combinations of shifts to find the global minimum.
0/257 completed