Levenshtein distance

In information theory, the Levenshtein distance or edit distance between two strings is given by the minimum number of operations needed to transform one string into the other, where an operation is an insertion, deletion, or substitution. It is named after the Russian scientist Vladimir Levenshtein, who considered this distance in 1965. It is useful in applications that need to determine how similar two strings are, such as spell checkers.

For example, the Levenshtein distance between "kitten" and "sitting" is 3, since these three edits change one into the other, and there is no way to do it with less than three edits:

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

It can be considered a generalization of the Hamming distance, which is used for strings of the same length and only considers substitution edits. There are also further generalizations of the Levenshtein distance that consider, for example, exchanging two characters as an operation.

Contents

The algorithm

A commonly-used bottom-up dynamic programming algorithm for computing the Levenshtein distance involves the use of an (n + 1) × (m + 1) matrix, where n and m are the lengths of the two strings. Here is pseudocode for a function LevenshteinDistance that takes two strings, str1 of length lenStr1, and str2 of length lenStr2, and computes the Levenshtein distance between them:

int LevenshteinDistance(char str1[1..lenStr1], char str2[1..lenStr2])
    // d is a table with lenStr1+1 rows and lenStr2+1 columns
    declare int d[0..lenStr1, 0..lenStr2]
    // i and j are used to iterate over str1 and str2
    declare int i, j, cost
  
    for i from 0 to lenStr1
        d[i, 0] := i
    for j from 0 to lenStr2
        d[0, j] := j
  
    for i from 1 to lenStr1
        for j from 1 to lenStr2
            if str1[i] = str2[j] then cost := 0
                                 else cost := 1
            d[i, j] := minimum(
                                 d[i-1, j  ] + 1,     // insertion
                                 d[i  , j-1] + 1,     // deletion
                                 d[i-1, j-1] + cost   // substitution
                             )
  
    return d[lenStr1, lenStr2]
 

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.

Possible improvements

Possible improvements to this algorithm include:

Proof of correctness

As mentioned earlier, the invariant is that we can transform the initial segment s[1..i] into t[1..j] using a minimum of d[i,j] operations. This invariant holds since:

This proof fails to validate that the number placed in d[i,j] is in fact minimal; this is more difficult to show, and involves an argument by contradiction in which we assume d[i,j] is smaller than the minimum of the three, and use this to show one of the three is not minimal.

Upper and lower bounds

The Levenshtein distance has several simple upper and lower bounds that are useful in applications which compute many of them and compare them. These include:

Sample implementations

Python

From http://hetland.org/python/distance.py by Magnus Lie Hetland

 def distance(a,b):
     "Calculates the Levenshtein distance between a and b."
     n, m = len(a), len(b)
     if n > m:
         # Make sure n <= m, to use O(min(n,m)) space
         a,b = b,a
         n,m = m,n
         
     current = range(n+1)
     for i in range(1,m+1):
         previous, current = current, [i]+[0]*m
         for j in range(1,n+1):
             add, delete = previous[j]+1, current[j-1]+1
             change = previous[j-1]
             if a[j-1] != b[i-1]:
                 change = change + 1
             current[j] = min(add, delete, change)
             
     return current[n]
 

Haskell

Because Haskell automatically memoizes results of previous calls, it is particularly suited to a simple recursive implementation:

editDistance :: String->String->Int
 editDistance [] [] = 0
 editDistance s [] = length s
 editDistance [] t = length t
 editDistance (s:ss) (t:ts) = minimum [ (if s == t then 0 else 1) + editDistance ss ts,
                                        1 + editDistance ss (t:ts),
                                        1 + editDistance (s:ss) ts ]
 

Scheme

Uses srfi-25 and srfi-42

 (define add1 (lambda (x) (+ x 1)))
 (define sub1 (lambda (x) (- x 1)))
 
 (define levenshtein-distance
   (lambda (s1 s2)
     (let* ((width (add1 (string-length s1)))
            (height (add1 (string-length s2)))
 	   (d (make-array (shape 0 height 0 width) 0)))
       (do-ec (:range x width) (array-set! d 0 x x))
       (do-ec (:range y height) (array-set! d y 0 y))
       (do-ec (:range x (string-length s1))
 	     (:range y (string-length s2))
              (array-set!
               d (add1 y) (add1 x)
               (min
                (add1 (array-ref d y (add1 x)))
                (add1 (array-ref d (add1 y) x))
                (+ (array-ref d y x)
                   (if (eqv? (string-ref s1 x)
                             (string-ref s2 y))
                       0
                       1)))))
       (displarray d)
       (array-ref d (sub1 height) (sub1 width)))))
 

See also

External links

See also: Levenshtein distance, Big O notation, Dynamic programming, Hamming distance, Haskell (programming language), Information theory, Invariant (mathematics), Memoization, Metric space, Parallel computing