Edit Distance
Also Levenshtein Distance · ED
The edit distance ED(x, y) (Levenshtein distance) is the minimal number of single-character insert, delete and replace operations that transform the string x into the string y.
Formula#
Recurrence (for ):
with and .
Dynamic programming. Fill an table with (row/column 0 = ):
- , ,
- with if , else ,
- result (bottom-right entry).
Each entry depends only on its left, upper and upper-left neighbour. Time and space ; space suffices, since only the previous row is needed.
Properties#
ProofProof sketches (recommended as exam preparation)
- Every operation can be undone by one operation (insert ↔ delete, replace ↔ replace); reversing an optimal sequence gives one of the same length.
- deletions suffice; each operation shortens by at most 1, so at least are needed.
- Each operation changes the length by at most 1, and the length must change from to .
- Transform into optimally, then replace by (or do nothing if they are equal).
- A single operation sequence only proves an upper bound on ED; the exact value needs the DP table or a lower-bound argument (e.g. property 3, or the Q-Gram Lemma read backwards).
- ED is the relevance model for fuzzy search on whole words; for search-as-you-type it is replaced by the Prefix Edit Distance.
Example#
DOOF → BOOF (replace(1,B)) → BLOF (replace(2,L)) → BLOE (replace(4,E)) → BLOED (insert(5,D)) proves . The table for shows equality:
| D | O | O | F | ||
|---|---|---|---|---|---|
| 0 | 1 | 2 | 3 | 4 | |
| B | 1 | 1 | 2 | 3 | 4 |
| L | 2 | 2 | 2 | 3 | 4 |
| O | 3 | 3 | 2 | 2 | 3 |
| E | 4 | 4 | 3 | 3 | 3 |
| D | 5 | 4 | 4 | 4 | 4 |
Every entry is the ED of two prefixes, e.g. ; the result is .
Exam WS 22/23, Task 2.1: via alfa → alpa (replace f by p) → alpha (insert h); at least 2 are needed, since by property 3 one operation would have to be an insert, but deleting any one character of alpha (lpha, apha, alha, alpa, alph) never gives alfa.
Sources#
- Slides 08, p. 8 (definition), p. 9 (properties), p. 10 (recurrence), p. 11 (DP table)
- DBIS_VL08 > Edit Distance, DBIS_VL08 > Recursive formula, DBIS_VL08 > Dynamic programming algorithm
- DBIS_VL13 > Example Task: Q-Grams and Edit Distance (WS 22/23, Task 2.2, 5 points)
- Exams: DBIS Exam WS1718 (not published) (Task 3), DBIS Exam WS2223 (not published) (Tasks 2.1–2.3)