Chapter 10 · Simulation

String Similarity: Levenshtein Distance

← Chapter 10

Ready.

Dynamic Programming Table

Distance —
Similarity —
Progress 0%

Step Explanation

String Similarity: Levenshtein Distance

The dynamic programming matrix is filled in step by step, showing how the costs of insertion, deletion and substitution determine the edit distance.

How to use

  • Enter two strings (up to 12 characters each) and press Build Matrix.
  • Step computes one cell, Auto Play fills in the rest of the table, Reset rebuilds the matrix.
  • The yellow cell is the one being computed; the three blue cells are the values it is derived from.

Recurrence

D[i][j] is the edit distance between the first i characters of A and the first j characters of B. The first row and column hold the distance from or to the empty string (ε): D[i][0] = i, D[0][j] = j.

D[i][j] = min(D[i−1][j] + 1, D[i][j−1] + 1, D[i−1][j−1] + cost), where cost = 0 if A[i−1] = B[j−1] and 1 otherwise.

  • Deletion (from above): A[i−1] is deleted.
  • Insertion (from the left): B[j−1] is inserted.
  • Substitution / match (diagonal): the character is replaced or kept.

The bottom-right cell is the Levenshtein distance. Normalized similarity = (1 − distance / max(|A|, |B|)) × 100%.

Complexity

O(|A|·|B|) time. The full table needs O(|A|·|B|) memory; if only the distance is needed, keeping two rows reduces this to O(min(|A|, |B|)).