Levenshtein Distance
Algorithm · Core
Step through it: Dynamic Programming pattern
Step 1 of 6
Goal: how many ways can you climb 5 stairs taking 1 or 2 steps at a time? You reach stair 5 from stair 4 or stair 3, so ways(5) = ways(4) + ways(3). Working that out naively repeats the same sub-questions many times. Instead write each answer down once.
Step 2 of 6
Base cases: there is 1 way to be on stair 0 (do nothing) and 1 way to reach stair 1.
Step 3 of 6
Stair 2 is reached from stair 1 or stair 0.
Step 4 of 6
Stair 3 comes from stairs 2 and 1.
Step 5 of 6
Stair 4: 3 + 2 = 5. Stair 5: 5 + 3 = 8. Each answer reuses two stored answers, so n stairs take n steps instead of exponential time. Storing sub-answers like this is dynamic programming.
Step 6 of 6
Your turn.
The Levenshtein distance is a string metric for measuring the difference between two sequences. Informally, the Levenshtein distance between two words is the minimum number of single-character edits (insertions, deletions or substitutions) required to change one word into the other.
Definition
Mathematically, the Levenshtein distance between two strings
a and b (of length |a| and |b| respectively) is given by
where
where
is the indicator function equal to 0 when
and equal to 1 otherwise, and
is the distance between the first i characters of a and the first
j characters of b.
Note that the first element in the minimum corresponds to
deletion (from a to b), the second to insertion and
the third to match or mismatch, depending on whether the
respective symbols are the same.
Example
For example, the Levenshtein distance between kitten and
sitting is 3, since the following three edits change one
into the other, and there is no way to do it with fewer than
three edits:
- kitten → sitten (substitution of "s" for "k")
- sitten → sittin (substitution of "i" for "e")
- sittin → sitting (insertion of "g" at the end).
Applications
This has a wide range of applications, for instance, spell checkers, correction systems for optical character recognition, fuzzy string searching, and software to assist natural language translation based on translation memory.
Dynamic Programming Approach Explanation
Let’s take a simple example of finding minimum edit distance between
strings ME and MY. Intuitively you already know that minimum edit distance
here is 1 operation, which is replacing E with Y. But
let’s try to formalize it in a form of the algorithm in order to be able to
do more complex examples like transforming Saturday into Sunday.
To apply the mathematical formula mentioned above to ME → MY transformation
we need to know minimum edit distances of ME → M, M → MY and M → M transformations
in prior. Then we will need to pick the minimum one and add one operation to
transform last letters E → Y. So minimum edit distance of ME → MY transformation
is being calculated based on three previously possible transformations.
To explain this further let’s draw the following matrix:
- Cell
(0:1)contains red number 1. It means that we need 1 operation to transformMto an empty string. And it is by deletingM. This is why this number is red. - Cell
(0:2)contains red number 2. It means that we need 2 operations to transformMEto an empty string. And it is by deletingEandM. - Cell
(1:0)contains green number 1. It means that we need 1 operation to transform an empty string toM. And it is by insertingM. This is why this number is green. - Cell
(2:0)contains green number 2. It means that we need 2 operations to transform an empty string toMY. And it is by insertingYandM. - Cell
(1:1)contains number 0. It means that it costs nothing to transformMintoM. - Cell
(1:2)contains red number 1. It means that we need 1 operation to transformMEtoM. And it is by deletingE. - And so on...
This looks easy for such small matrix as ours (it is only 3x3). But here you
may find basic concepts that may be applied to calculate all those numbers for
bigger matrices (let’s say a 9x7 matrix for Saturday → Sunday transformation).
According to the formula you only need three adjacent cells (i-1:j), (i-1:j-1), and (i:j-1) to
calculate the number for current cell (i:j). All we need to do is to find the
minimum of those three cells and then add 1 in case if we have different
letters in i's row and j's column.
You may clearly see the recursive nature of the problem.
Let's draw a decision graph for this problem.
You may see a number of overlapping sub-problems on the picture that are marked with red. Also there is no way to reduce the number of operations and make it less than a minimum of those three adjacent cells from the formula.
Also you may notice that each cell number in the matrix is being calculated based on previous ones. Thus the tabulation technique (filling the cache in bottom-up direction) is being applied here.
Applying this principle further we may solve more complicated cases like
with Saturday → Sunday transformation.
Code
/**
* @param {string} a
* @param {string} b
* @return {number}
*/
export default function levenshteinDistance(a, b) {
// Create empty edit distance matrix for all possible modifications of
// substrings of a to substrings of b.
const distanceMatrix = Array(b.length + 1).fill(null).map(() => Array(a.length + 1).fill(null));
// Fill the first row of the matrix.
// If this is first row then we're transforming empty string to a.
// In this case the number of transformations equals to size of a substring.
for (let i = 0; i <= a.length; i += 1) {
distanceMatrix[0][i] = i;
}
// Fill the first column of the matrix.
// If this is first column then we're transforming empty string to b.
// In this case the number of transformations equals to size of b substring.
for (let j = 0; j <= b.length; j += 1) {
distanceMatrix[j][0] = j;
}
for (let j = 1; j <= b.length; j += 1) {
for (let i = 1; i <= a.length; i += 1) {
const indicator = a[i - 1] === b[j - 1] ? 0 : 1;
distanceMatrix[j][i] = Math.min(
distanceMatrix[j][i - 1] + 1, // deletion
distanceMatrix[j - 1][i] + 1, // insertion
distanceMatrix[j - 1][i - 1] + indicator, // substitution
);
}
}
return distanceMatrix[b.length][a.length];
}References
Practice
Dynamic Programming
- Climbing StairsEasy
- Fibonacci NumberEasy
- Min Cost Climbing StairsEasy
- Pascal's TriangleEasy
- House RobberMedium
- House Robber IIMedium
- Coin ChangeMedium
- Coin Change IIMedium
- Longest Increasing SubsequenceMedium
- Longest Common SubsequenceMedium
- Word BreakMedium
- Unique PathsMedium
- Unique Paths IIMedium
- Minimum Path SumMedium
- Jump GameMedium
- Partition Equal Subset SumMedium
- Target SumMedium
- Decode WaysMedium
- Maximum Product SubarrayMedium
- Longest Palindromic SubstringMedium
- Palindromic SubstringsMedium
- Best Time to Buy and Sell Stock with CooldownMedium
- TriangleMedium
- Maximal SquareMedium
- Edit DistanceHard
- Regular Expression MatchingHard
- Burst BalloonsHard
- Distinct SubsequencesHard
- Longest Valid ParenthesesHard
- Best Time to Buy and Sell Stock IVHard
String Matching
- Find the Index of the First Occurrence in a StringEasy
- Repeated Substring PatternEasy
- Is SubsequenceEasy
- Rotate StringEasy
- Longest Palindromic SubstringMedium
- Palindromic SubstringsMedium
- Repeated String MatchMedium
- One Edit DistanceMedium
- Shortest PalindromeHard
- Longest Happy PrefixHard
- Longest Duplicate SubstringHard
- Edit DistanceHard
- Wildcard MatchingHard
Spotted a mistake or something unclear? Report it on GitHub.