Levenshtein Distance Algorithm for Approximate String Matching
The Levenshtein distance (also known as edit distance) measures the minimum number of single-character insertions, deletions, or substitutions required to transform one string s into another string t. It is a foundational metric for approximate string matching, where you can use the computed distance (or a threshold, e.g., distance ≤ k) to identify similar strings, such as spell-checking or fuzzy search.
This algorithm uses dynamic programming (DP) to compute the distance efficiently. It builds a matrix where each cell represents the distance for prefixes of the strings.
Key Properties
Operations cost: Each insertion, deletion, or substitution costs 1.
Time complexity: O(m * n), where m = len(s), n = len(t).
Space complexity: O(m * n) for the full DP table; optimizable to O(min(m, n)) using two rows.
Dynamic Programming Formulation
Let dp[i][j] be the Levenshtein distance between the prefix s[0..i-1] and t[0..j-1].
Initialization:
dp[i][0] = i for i = 0 to m (cost of deleting i characters from s)
dp[0][j] = j for j = 0 to n (cost of inserting j characters into s)
Recurrence (for i = 1 to m, j = 1 to n):
code
if s[i-1] == t[j-1]:
dp[i][j] = dp[i-1][j-1] // No operation needed
else:
dp[i][j] = 1 + min(
dp[i-1][j-1], // Substitution
dp[i-1][j], // Deletion from s
dp[i][j-1] // Insertion into s
)
The final distance is dp[m][n].
Pseudocode
python
def levenshtein_distance(s: str, t: str) -> int:
m, n = len(s), len(t)
dp = [[0] * (n + 1) for _ in range(m + 1)]
# Initialize
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
# Fill DP table
for i in range(1, m + 1):
for j in range(1, n + 1):
if s[i-1] == t[j-1]:
dp[i][j] = dp[i-1][j-1]
else:
dp[i][j] = 1 + min(
dp[i-1][j-1], # Substitute
dp[i-1][j], # Delete
dp[i][j-1] # Insert
)
return dp[m][n]
Example
Compute distance between s = "kitten" (m=6) and t = "sitting" (n=7):
""
s
i
t
t
i
n
g
""
0
1
2
3
4
5
6
7
k
1
1
2
3
4
5
6
7
i
2
2
1
2
3
4
5
6
t
3
3
2
1
2
3
4
5
t
4
4
3
2
2
2
3
4
e
5
5
4
3
3
3
3
4
n
6
6
5
4
4
4
2
3
dp[6][7] = 3 (e.g., substitute 's' for 'k', substitute 'e' for 'i', insert 'g').
For Approximate String Matching in Practice
Pairwise matching: Use levenshtein_distance(query, candidate) ≤ k (e.g., k=2 for typos).
Dictionary search: Compute distance to all words in a list; return top-k lowest distances.
Indexing optimizations (for large-scale):
BK-trees or tries for sublinear queries.
Locality-sensitive hashing (LSH) for very large corpora.
Space optimization (use only two rows):
python
# Replace full dp with prev_row and curr_row arrays of size n+1
This DP algorithm is robust, correct, and widely used (e.g., in diff tools, spell-checkers). For very long strings, consider approximations like Ukkonen's banded DP (O(k * n) for small k).