Levenshtein Distance

Decision Sciences
Introduced by
Vladimir Levenshtein
Year
1966
Type
Edit distance metric
Family
String/sequence distance

What does it do?

Levenshtein distance, also called edit distance, is the minimum number of single-character insertions, deletions and substitutions needed to turn one string into another.

Introduced by Vladimir Levenshtein in 1966, the standard unit-cost version is a metric and is used in computational linguistics, spell checking, DNA sequence comparison and record linkage. Its value ranges from 0 for identical strings to the length of the longer string.

The intuition behind the method

Consider turning 'kitten' into 'sitting'. One minimal sequence of edits is: substitute 'k' with 's', substitute 'e' with 'i', and insert 'g' at the end, giving three operations. Levenshtein distance is the smallest number of such operations that achieves the transformation. It is useful when small changes such as typos or sequence mutations are expected to indicate similarity, because the count grows with the number of edits needed rather than with the length of the strings alone.

History

Vladimir Levenshtein introduced the distance in 1966 in a paper on binary codes correcting deletions, insertions and reversals, which is the source usually cited for the metric. Fred J. Damerau's 1964 paper describes a method for detecting and correcting spelling errors in dictionary words, where a word is assumed to contain at most one error, such as a wrong, missing, extra or transposed letter. It is a related spelling-correction technique rather than the edit distance itself. The Damerau-Levenshtein variant, which adds transposition of adjacent characters, and weighted edit distance extend the basic metric.

When to use it

Choose Levenshtein distance when the data are sequences of discrete symbols such as characters, tokens, nucleotides or amino acids, and the differences of interest are insertions, deletions and substitutions, as with typing errors or name variants. It handles strings of different lengths, which Hamming distance cannot. Avoid it for numeric time series, where dynamic time warping is the usual alternative, and when phonetic or semantic similarity matters, since the standard metric does not encode either. For very long sequences or many pairwise comparisons, the quadratic cost argues for indexing structures such as BK-trees or bounded algorithms that stop once a threshold is exceeded.

Limitations and considerations

  • Exact computation takes O(n*m) time and, in the full form, O(n*m) memory for strings of length n and m, which becomes costly for long sequences or large-scale matching.
  • With default costs every substitution is treated equally, so a pair of characters that are visually or phonetically close costs the same as an unrelated pair unless custom costs are set.
  • Under unit costs an adjacent transposition such as 'ab' to 'ba' requires two operations, which is why transposition-aware variants are used when swapped letters are a common error.
  • The raw distance is an absolute count bounded by string length, so pairs of long strings are not directly comparable with pairs of short strings unless it is normalised by length.

Source conditions do not replace independent scientific review or validation by an analysis engine.

Strengths

  • The unit-cost version is a metric: distances are non-negative, zero only for identical strings, symmetric, and satisfy the triangle inequality.
  • Each unit of distance corresponds to a concrete insertion, deletion or substitution that can be listed by tracing back through the matrix, so the result can be inspected.
  • It applies to strings of different lengths, unlike Hamming distance, which requires equal lengths.
  • Operation costs can be weighted to reflect a domain's error process, which allows the same recurrence to be adapted.

Applications

  • Spell checking and autocorrect: measuring distance from typed words to dictionary entries
  • DNA and protein sequence alignment: comparing biological sequences to identify mutations
  • Record linkage and deduplication: matching similar names or identifiers across databases
  • Approximate string matching: finding near-matches in search applications
  • Code plagiarism detection: comparing programming code snippets for similarity

How it works

How it works

1

Create a matrix with one row for each prefix of the first string (plus an empty prefix) and one column for each prefix of the second. The first row and first column hold the cumulative cost of deleting or inserting characters, so cell [i,0] equals i and cell [0,j] equals j under unit costs.

2

Fill the matrix row by row. Each cell [i,j] is the minimum of three options: the diagonal cell plus 0 if the two characters are equal or plus 1 if they differ (substitution), the cell above plus 1 (deletion), and the cell to the left plus 1 (insertion).

3

The bottom-right cell holds the Levenshtein distance. To recover the edit sequence, trace back from that cell to the origin, following the option that produced each minimum.

Common pitfalls

  • Confusing Levenshtein distance with Hamming distance; Hamming requires equal-length strings, Levenshtein does not.
  • Assuming unweighted cost (all edits cost 1) when weighted costs (substitution=2, insertion=1) might be more appropriate for the data.
  • Applying Levenshtein to numeric time series, where values are compared by magnitude rather than as symbol sequences; a distance built for numbers, such as dynamic time warping, is the usual choice.
  • Ignoring the O(n*m) complexity and applying it naively to very long strings or massive datasets.
  • Assuming that a 'Damerau-Levenshtein' label guarantees a metric: the restricted (optimal string alignment) form does not satisfy the triangle inequality, whereas the unrestricted form does.

Frequently asked questions

What is the difference between Levenshtein and Hamming distance?

Hamming distance only works on strings of equal length and counts the number of differing positions. Levenshtein distance works on strings of any length and counts the minimum edit operations (insertions, deletions, substitutions). Levenshtein is more general.

Is Levenshtein distance case-sensitive?

By default, yes. 'Cat' and 'cat' have a Levenshtein distance of 1 (one substitution). Normalize case before comparison if case-insensitivity is desired.

Can I use custom costs for different edit operations?

Yes. Weighted edit distance assigns a separate cost to each insertion, deletion and substitution, and the same dynamic programming recurrence is used with those costs in place of unit costs. The result depends on the chosen costs, so they should reflect the error process in your data. A restricted edit distance, which limits which operations or combinations are allowed, is a separate concept and is not the same as weighted costs.

How do I optimize Levenshtein distance for long strings?

Store only two rows of the matrix, which reduces memory to a function of the shorter string's length; this gives the distance only, since recovering the edit sequence requires the full matrix or a separate traceback. For searching a dictionary, BK-trees index strings by distance. If you only need to know whether two strings lie within a threshold, bounded algorithms can stop once the threshold is exceeded.

Related methods

Sources

  1. Levenshtein, V. I. (1966). Binary codes capable of correcting deletions, insertions, and reversals. Soviet Physics Doklady, 10, 707-710.

    Open publication reference
  2. Damerau, F. J. (1964). A technique for computer detection and correction of spelling errors. Communications of the ACM, 7(3), 171-176.

    Open DOI reference