Levenshtein distance

In information theory, linguistics, and computer science, the Levenshtein distance is a string metric for measuring the difference between two sequences. 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. It is named after Soviet mathematician Vladimir Levenshtein, who defined the metric in 1965.

Levenshtein distance may also be referred to as edit distance, although that term may also denote a larger family of distance metrics known collectively as edit distance. It is closely related to pairwise string alignments.

Definition
The Levenshtein distance between two strings $$a, b$$ (of length $$|a|$$ and $$|b|$$ respectively) is given by $$\operatorname{lev}(a, b)$$ where


 * $$\operatorname{lev}(a, b) = \begin{cases}

|a| & \text{ if } |b| = 0, \\ |b| & \text{ if } |a| = 0, \\ \operatorname{lev}\big(\operatorname{tail}(a),\operatorname{tail}(b)\big) & \text{ if } \operatorname{head}(a)= \operatorname{head}(b), \\ 1 + \min \begin{cases} \operatorname{lev}\big(\operatorname{tail}(a), b\big) \\ \operatorname{lev}\big(a, \operatorname{tail}(b)\big) \\ \operatorname{lev}\big(\operatorname{tail}(a), \operatorname{tail}(b)\big) \\ \end{cases} & \text{ otherwise} \end{cases}$$ where the $$\operatorname{tail}$$ of some string $$x$$ is a string of all but the first character of $$x$$ (i.e. $$\operatorname{tail}(x_0x_1 \dots x_n)=x_1x_2 \dots x_n$$), and $$\operatorname{head}(x)$$ is the first character of $$x$$ (i.e. $$\operatorname{head}(x_0x_1 \dots x_n)=x_0$$). Either the notation $$x[n]$$ or $$x_n$$ is used to refer the $$n$$th character of the string $$x$$, counting from 0, thus $$\operatorname{head}(x)=x_0=x[0]$$.

The first element in the minimum corresponds to deletion (from $$a$$ to $$b$$), the second to insertion and the third to replacement.

This definition corresponds directly to the naive recursive implementation.

Example


For example, the Levenshtein distance between "kitten" and "sitting" is 3, since the following 3 edits change one into the other, and there is no way to do it with fewer than 3 edits:
 * 1) kitten → sitten (substitution of "s" for "k"),
 * 2) sitten → sittin (substitution of "i" for "e"),
 * 3) sittin → sitting (insertion of "g" at the end).

A simple example of a deletion can be seen with "uninformed" and "uniformed" which have a distance of 1:
 * 1) uninformed → uniformed (deletion of "n").

Upper and lower bounds
The Levenshtein distance has several simple upper and lower bounds. These include:
 * It is at least the absolute value of the difference of the sizes of the two strings.
 * It is at most the length of the longer string.
 * It is zero if and only if the strings are equal.
 * If the strings have the same size, the Hamming distance is an upper bound on the Levenshtein distance. The Hamming distance is the number of positions at which the corresponding symbols in the two strings are different.
 * The Levenshtein distance between two strings is no greater than the sum of their Levenshtein distances from a third string (triangle inequality).

An example where the Levenshtein distance between two strings of the same length is strictly less than the Hamming distance is given by the pair "flaw" and "lawn". Here the Levenshtein distance equals 2 (delete "f" from the front; insert "n" at the end). The Hamming distance is 4.

Applications
In approximate string matching, the objective is to find matches for short strings in many longer texts, in situations where a small number of differences is to be expected. The short strings could come from a dictionary, for instance. Here, one of the strings is typically short, while the other is arbitrarily long. This has a wide range of applications, for instance, spell checkers, correction systems for optical character recognition, and software to assist natural-language translation based on translation memory.

The Levenshtein distance can also be computed between two longer strings, but the cost to compute it, which is roughly proportional to the product of the two string lengths, makes this impractical. Thus, when used to aid in fuzzy string searching in applications such as record linkage, the compared strings are usually short to help improve speed of comparisons.

In linguistics, the Levenshtein distance is used as a metric to quantify the linguistic distance, or how different two languages are from one another. It is related to mutual intelligibility: the higher the linguistic distance, the lower the mutual intelligibility, and the lower the linguistic distance, the higher the mutual intelligibility.

Relationship with other edit distance metrics
There are other popular measures of edit distance, which are calculated using a different set of allowable edit operations. For instance,
 * the Damerau–Levenshtein distance allows the transposition of two adjacent characters alongside insertion, deletion, substitution;
 * the longest common subsequence (LCS) distance allows only insertion and deletion, not substitution;
 * the Hamming distance allows only substitution, hence, it only applies to strings of the same length.
 * the Jaro distance allows only transposition.

Edit distance is usually defined as a parameterizable metric calculated with a specific set of allowed edit operations, and each operation is assigned a cost (possibly infinite). This is further generalized by DNA sequence alignment algorithms such as the Smith–Waterman algorithm, which make an operation's cost depend on where it is applied.

Recursive
This is a straightforward, but inefficient, recursive Haskell implementation of a  function that takes two strings, s and t, together with their lengths, and returns the Levenshtein distance between them:

This implementation is very inefficient because it recomputes the Levenshtein distance of the same substrings many times.

A more efficient method would never repeat the same distance calculation. For example, the Levenshtein distance of all possible suffixes might be stored in an array $$M$$, where $$M[i][j]$$ is the distance between the last $$i$$ characters of string  and the last $$j$$ characters of string. The table is easy to construct one row at a time starting with row 0. When the entire table has been built, the desired distance is in the table in the last row and column, representing the distance between all of the characters in  and all the characters in.

Iterative with full matrix
This section uses 1-based strings rather than 0-based strings. If m is a matrix, $$m[i,j]$$ is the ith row and the jth column of the matrix, with the first row having index 0 and the first column having index 0.

Computing the Levenshtein distance is based on the observation that if we reserve a matrix to hold the Levenshtein distances between all prefixes of the first string and all prefixes of the second, then we can compute the values in the matrix in a dynamic programming fashion, and thus find the distance between the two full strings as the last value computed.

This algorithm, an example of bottom-up dynamic programming, is discussed, with variants, in the 1974 article The String-to-string correction problem by Robert A. Wagner and Michael J. Fischer.

This is a straightforward pseudocode implementation for a function  that takes two strings, s of length m, and t of length n, and returns the Levenshtein distance between them:

Two examples of the resulting matrix (hovering over a tagged number reveals the operation performed to get that number):


 * {|class="wikitable"

! k ! i ! t ! t ! e ! n ! s ! i ! t !t ! i ! n ! g
 * ||0 ||1 ||2 ||3 ||4 ||5 ||6
 * ||0 ||1 ||2 ||3 ||4 ||5 ||6
 * 1 ||1 ||2 ||3 ||4 ||5 ||6
 * 2 ||2 ||1 ||2 ||3 ||4 ||5
 * 3 ||3 ||2 ||1 ||2 ||3 ||4
 * 4 ||4 ||3 ||2 ||1 ||2 ||3
 * 5 ||5 ||4 ||3 ||2 ||2 ||3
 * 6 ||6 ||5 ||4 ||3 ||3 ||2
 * 7 ||7 ||6 ||5 ||4 ||4 ||3
 * }

The invariant maintained throughout the algorithm is that we can transform the initial segment into  using a minimum of  operations. At the end, the bottom-right element of the array contains the answer.

Iterative with two matrix rows
It turns out that only two rows of the table – the previous row and the current row being calculated –  are needed for the construction, if one does not want to reconstruct the edited input strings.

The Levenshtein distance may be calculated iteratively using the following algorithm:

Hirschberg's algorithm combines this method with divide and conquer. It can compute the optimal edit sequence, and not just the edit distance, in the same asymptotic time and space bounds.

Automata
Levenshtein automata efficiently determine whether a string has an edit distance lower than a given constant from a given string.

Approximation
The Levenshtein distance between two strings of length $n$ can be approximated to within a factor


 * $$(\log n)^{O(1/\varepsilon)},$$

where $ε > 0$ is a free parameter to be tuned, in time $O(n^{1 + ε})$.

Computational complexity
It has been shown that the Levenshtein distance of two strings of length $n$ cannot be computed in time $O(n^{2 − ε})$ for any ε greater than zero unless the strong exponential time hypothesis is false.