v9.1.1
Menu

Levenshtein Distance

easyFREEMachine TranslationNLP 3: Advanced

Compute the Levenshtein (edit) distance between two strings. The edit distance is the minimum number of single-character operations (insertions, deletions, substitutions) needed to transform one string into another.

Implement levenshtein(s1, s2).

Input:

  • s1: First string
  • s2: Second string

Output: Return an integer (the edit distance).

Example

Input
kitten
sitting
Output
3
Reasoning
  • Inputs: s1 is kitten (6 letters), s2 is sitting (7 letters). Every insert, delete or substitute costs 1.
  • Line them up: keep the letters of kitten in order and set them against sitting, leaving the final g unmatched:
k i t t e n -
s i t t i n g
  • Four columns agree (i, t, t, n) and cost nothing. k vs s and e vs i are two substitutions; the gap opposite g is one insertion. Total: 1+1+1=31 + 1 + 1 = 3, the output 3.
  • Why not fewer: the lengths differ by 7−6=17 - 6 = 1, so at least one insertion is unavoidable. With only one, the six letters of kitten sit opposite six of the seven letters of sitting, and the best such pairing still leaves 2 mismatches. So 3 is the minimum.
  • Notice: the distance counts only the cheapest edit sequence. Identical strings score 0, and against an empty string the distance is the other string's length (every character is inserted).

Constraints

  • Strings can be empty
  • Operations: insert, delete, substitute (each costs 1)
  • Output: Single integer

More from NLP 3: Advanced

solution.py

Test results

Sign in to run your code against the test cases.