Solution: The Edit Distance Problem
This review provides a detailed analysis of three different ways to solve the famous edit distance problem.
We'll cover the following...
Solution #1: Brute force
Let’s start by looking at the brute force solution to solve this problem first:
Explanation
We process all the characters of each string one by one. There are two possibilities for every pair of characters being considered:
-
The end characters of both the strings match. In which case, the lengths of both the strings are reduced by one and the function is called recursively on the remaining strings (lines 17-18).
-
The end characters of both the strings do not match. In which case, all three operations (insertion, deletion, and substitution) are carried out on the last character of the first string (lines 22-24).
-
The minimum cost for all three operations is computed recursively and returned (lines 22-24).
Time complexity
The time complexity of this code is exponential, i.e., ...