Skip to main content

Levenshtein Distance

Definition​

The Levenshtein Distance Algorithm is a dynamic programming technique used to measure the similarity between two strings by calculating the minimum number of single-character edits (insertions, deletions, or substitutions) required to transform one string into another

Practice​

levenshteinDistance(str1, str2):
m = length(str1)
n = length(str2)
matrix = new matrix[m+1][n+1]

// Initialize first row and column
for i from 0 to m:
matrix[i][0] = i
for j from 0 to n:
matrix[0][j] = j

// Fill the matrix
for i from 1 to m:
for j from 1 to n:
cost = 0 if str1[i-1] == str2[j-1] else 1
insertion = matrix[i][j-1] + 1
deletion = matrix[i-1][j] + 1
substitution = matrix[i-1][j-1] + cost
matrix[i][j] = min(insertion, deletion, substitution)

return matrix[m][n]