Edit distance

Edit Distance is a standard Dynamic Programming problem. Given two strings $$s_1$$ and $$s_2$$, the edit distance between $$s_1$$ and $$s_2$$ is the minimum number of operations required to convert string $$s_1$$ to $$s_2$$. The following operations are typically used:


 * 1) Replacing one character of string by another character.
 * 2) Deleting a character from string
 * 3) Adding a character to string

Brute-Force Approach

 * If characters to be compared are equal i.e. s1[m] = s2[n], then we will compare (m+1)th character of s1 to (n+1)th character of s2 (if both exist).
 * If we replace one character of string s1 then we will compare (m+1)th character of s1 to (n+1)th character of s2 (if both exist).
 * If we insert one character to string s1 then we will compare mth character of s1 to (n+1)th character of s2 (if both exist).
 * If we delete one character from string s1 then we will compare (m+1)th character of s1 to nth character of s2 (if both exist).

Pseudocode for edit distance can be written using recursion easily:

Dynamic Programming Approach
If we use Dynamic Programming, then we can find the Edit Distance in $$O(|s1|*|s2|)$$, here |s1| denote length of string s1 and |s2| denote length of string s2.

Code for Edit Distance using dynamic programming is as follows:

Note that the space requirement can be improved to $$O(n)$$, as in each iteration only requires element from the current and previous row.

Variations
Variations of Edit Distance problem includes one where the cost of each operation is not the same.