Edit Distance (Levenshtein) visualization

Minimum inserts, deletes and substitutions to turn one string into another.

dp[i][j] = cost to convert a[0..i) into b[0..j). If the characters match, it is free (diagonal); otherwise 1 + the cheapest of delete (up), insert (left) or replace (diagonal).

Edge cases: converting to/from an empty string costs its length (the first row and column).

Complexity

Time: best O(m·n), average O(m·n), worst O(m·n). Space: O(m·n). Difficulty: Intermediate.

Pseudocode

procedure editDistance(a, b):
  dp[i][0] ← i; dp[0][j] ← j
  for i ← 1 to m:
    for j ← 1 to n:
      if a[i] = b[j]: dp[i][j] ← dp[i−1][j−1]
      else: dp[i][j] ← 1 + min(dp[i−1][j], dp[i][j−1], dp[i−1][j−1])
  return dp[m][n]

More dynamic programming algorithms