Levenshtein distance

Have you ever typed a word wrong and had your phone instantly suggest the correction? Or perhaps wondered how DNA sequences are compared across species? The answer often lies in the elegant mathematical concept of Levenshtein distance—a powerful tool that quantifies the difference between two sequences of characters. It's a fundamental idea underpinning everything from spell checkers to the study of language evolution, and it's far more intuitive than it sounds. Levenshtein distance measures the minimum number of single-character edits (insertions, deletions, or substitutions) required to transform one string into another. This concept is crucial for applications like spell checkers, search engines, and even comparing genetic sequences, helping computers understand 'close enough' matches. The most efficient way to compute Levenshtein distance uses dynamic programming, building a matrix to store and reuse calculations for smaller parts of the strings.

Source: Wikipedia

AI Summary

Have you ever typed a word wrong and had your phone instantly suggest the correction? Or perhaps wondered how DNA sequences are compared across species? The answer often lies in the elegant mathematical concept of Levenshtein distance—a powerful tool that quantifies the difference between two sequences of characters. It's a fundamental idea underpinning everything from spell checkers to the study of language evolution, and it's far more intuitive than it sounds.

The Levenshtein Distance: Measuring String Differences

At its heart, the Levenshtein distance is a surprisingly elegant way to measure how different two sequences of characters, or strings, truly are. It was first introduced in 1965 by Soviet mathematician Vladimir Levenshtein, forever linking his name to this fundamental concept in information theory and computer science.

Imagine you have two words, and you want to know how many changes it takes to turn one into the other. The Levenshtein distance counts the minimum number of single-character edits needed. These 'edits' are simple, atomic operations: inserting a character, deleting a character, or substituting one character for another.

More Than Just a Name

While we call it Levenshtein distance, you might also hear it referred to simply as 'edit distance.' However, 'edit distance' can be a broader term encompassing other metrics that use different sets of allowed operations or assign different costs to those operations. Levenshtein distance focuses specifically on those three core edits.

How It Works: A Classic Example

Let's take the classic example: transforming "kitten" into "sitting." How many edits do you think it takes? The Levenshtein distance here is 3. Here's one path to get there, and it's the most efficient:

1. kitten → sitten (substitution of 'k' for 's') 2. sitten → sittin (substitution of 'e' for 'i') 3. sittin → sitting (insertion of 'g' at the end)

It's all about finding that minimum number of changes. You could probably think of other ways to change "kitten" to "sitting," but they would involve more than three steps. That's the key: the Levenshtein distance always gives you the shortest path.

The Mathematical Heart

Mathematically, the Levenshtein distance between two strings, say a and b, of lengths m and n respectively, can be defined recursively. It considers the cost of three basic operations at each step: deletion, insertion, or substitution.

When comparing characters ai and bj (the i-th character of a and j-th of b), we look at the minimum cost of three paths: deleting ai, inserting bj, or substituting ai with bj (or matching them if they're the same). This forms the core recurrence relation for the distance d(i, j):

Here, $\mathbb{I}(ai \neq bj)$ is an indicator function, which equals 1 if the characters are different (cost of substitution) and 0 if they are the same (cost of a match). The base cases handle comparisons with empty strings, where the distance is simply the length of the non-empty string, representing all insertions or deletions needed.

\operatorname{d}(i,j) = \begin{cases} j & \text{if } i = 0 \\ i & \text{if } j = 0 \\ \min \begin{cases} \operatorname{d}(i-1, j) + 1 \\ \operatorname{d}(i, j-1) + 1 \\ \operatorname{d}(i-1, j-1) + \mathbb{I}(a_i \neq b_j) \end{cases} & \text{otherwise} \end{cases}

Measuring Differences: Levenshtein vs. Hamming

You might wonder how Levenshtein distance compares to other ways of measuring string differences, like Hamming distance. Hamming distance is simpler: it counts how many positions have different characters in strings of the same length. It only allows substitutions.

Consider "flaw" and "lawn." Their Levenshtein distance is 2 (delete 'f', insert 'n'). But their Hamming distance would be 4, as all four positions are different if we just compare them directly. This highlights Levenshtein's flexibility in handling differing lengths and insertions/deletions, not just substitutions.

Real-World Impact

Levenshtein distance is a workhorse in many practical applications, especially those involving 'approximate string matching.' When you search for something online, or your spell checker corrects a typo, there's a good chance Levenshtein distance (or a similar metric) is working behind the scenes. It helps computers understand what we meant to type.

Beyond simple typos, it's vital for correcting errors in optical character recognition (OCR) systems, finding similar records in databases (record linkage), and even in sophisticated natural language processing tools like translation memory software. It lets systems cope with slight variations and imperfections in data.

In linguistics, it's used to quantify the 'linguistic distance' between languages or dialects, giving insights into how different they are from each other. A higher Levenshtein distance between two languages often correlates with lower mutual intelligibility, meaning speakers would struggle more to understand each other.

How to Calculate It Efficiently

Dynamic Programming

While the recursive definition is elegant, directly implementing it can be incredibly inefficient, as it recomputes the same sub-problems over and over. This is where a powerful algorithmic technique called dynamic programming comes into play.

Instead of repeating calculations, dynamic programming builds a matrix (a grid) to store the Levenshtein distances between all possible prefixes of the two strings. We start by filling in the simplest cases—comparing empty strings to prefixes—and then build up the solution cell by cell.

Each cell in the matrix, d[i, j], represents the distance between the first i characters of string s and the first j characters of string t. By looking at the values in the cells to its left, above, and diagonally above-left, we can efficiently calculate the current cell's value, avoiding redundant work. The final answer, the distance between the two full strings, sits in the bottom-right corner of this matrix.

The Cost of Calculation

The dynamic programming approach allows us to compute the Levenshtein distance between two strings of length m and n in a time proportional to their product—that is, O(mn). This makes it practical for comparing relatively short strings.

However, for extremely long strings, like entire books or massive genomic sequences, this O(mn) complexity can still become computationally expensive. Researchers continue to explore optimizations and alternative algorithms for specific use cases, though the O(mn) lower bound remains a fundamental challenge in general scenarios.

Article

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. It is closely related to pairwise string alignments.

Definition

Levenshtein distance

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

${\displaystyle \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 ${\displaystyle \operatorname {tail} }$ of some string ${\displaystyle x}$ is a string of all but the first character of ${\displaystyle x}$ (i.e. ${\displaystyle \operatorname {tail} (x{0}x{1}\dots x{n})=x{1}x{2}\dots x{n}}$), and ${\displaystyle \operatorname {head} (x)}$ is the first character of ${\displaystyle x}$ (i.e. ${\displaystyle \operatorname {head} (x{0}x{1}\dots x{n})=x{0}}$). Either the notation ${\displaystyle x[n]}$ or ${\displaystyle x{n}}$ is used to refer to the ${\displaystyle n}$th character of the string ${\displaystyle x}$, counting from 0, thus ${\displaystyle \operatorname {head} (x)=x{0}=x}$.

The first element in the minimum corresponds to deletion (from ${\displaystyle a}$ to ${\displaystyle 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:

• kitten → sitten (substitution of "s" for "k"), • sitten → sittin (substitution of "i" for "e"), • 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:

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

Levenshtein distance

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.

The Levenshtein distance can be used to quantify the performance of listeners during speech-identification tests, for various applications such as speech audiometry. In this context, Levenshtein distances are calculated to quantify the distance between the stimuli that were presented to the listener and the sequence of phonemes that were identified. The cost associated with phoneme substitutions can either be fixed or depend on the number of phonological features that differ between the two substituted phonemes.

In bioinformatics, the Levenshtein distance and similar algorithms measure the difference between biological sequences, such as those of DNA and protein. The edits in the algorithm correspond to genetic mutations: an insertion, deletion, or substitution of a nucleotide (in DNA) or an amino acid (in protein). A lower distance between two sequences can indicate a closer evolutionary or functional relationship.

Relationship with other edit distance metrics

Levenshtein distance

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.

Computation

Recursive

This is a straightforward, but inefficient, recursive Haskell implementation of a lDistance 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 ${\displaystyle M}$, where ${\displaystyle M[i][j]}$ is the distance between the last ${\displaystyle i}$ characters of string s and the last ${\displaystyle j}$ characters of string t. 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 s and all the characters in t.

Iterative with full matrix

This section uses 1-based strings rather than 0-based strings. If m is a matrix, ${\displaystyle 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 LevenshteinDistance 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):

The invariant maintained throughout the algorithm is that we can transform the initial segment s[1..i] into t[1..j] using a minimum of d[i, j] 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

where ε > 0 is a free parameter to be tuned, in time O(n1 + ε).. Ten years later, researchers discovered an algorithm with the same running time but an approximation factor of f(1/ε), for some function f depending only on ε .

Computational complexity

It has been shown that the Levenshtein distance of two strings of length n cannot be computed in time O(n2 − ε) for any ε greater than zero unless the strong exponential time hypothesis is false. Another (unconditional) lower bound on the complexity of this problem is ${\displaystyle \Omega (mn)}$ in a model where the only query on symbols of the strings is comparison of two symbols.