Lably
Skip to content

Levenshtein distance

String metric for measuring edit distance

  • 7 min read
  • 7 chapters

Related on Lably

Through Linguistics, Computer science and Triangle inequality

The distance is named after Soviet mathematician Vladimir Levenshtein, who introduced it in 1965 in the context of error-correcting codes. Levenshtein distance is a particular form of edit distance; the latter term is also used for broader models in which the set of allowed operations or their costs differ. It is closely related to sequence alignment.

Definition

Let a=a1a2…am and b=b1b2…bn be two strings. Define D(i,j) as the Levenshtein distance between the prefixes a1…ai and b1…bj.

The boundary conditions are

D(i,0)=i,D(0,j)=j.

For i>0 and j>0,

D(i,j)=min{D(i−1,j)+1,D(i,j−1)+1,D(i−1,j−1)+δ(ai,bj),

where

δ(ai,bj)={0,ai=bj,1,ai≠bj.

The three alternatives correspond, respectively, to deleting ai, inserting bj, and either matching or substituting the final symbols of the two prefixes.

The Levenshtein distance between the full strings is D(m,n).

Example

The Levenshtein distance between kitten and sitting is 3. One optimal edit script is:

  1. kitten → sitten (substitute s for k);
  2. sitten → sittin (substitute i for e);
  3. sittin → sitting (insert g at the end).

A simple deletion example is uninformed → uniformed, which has distance 1.

Sign in to keep reading

6 more chapters are free with a Lably account.

More in Computing and communication