Search RU
Tasks / Algorithms / Edit distance
Statement hard

Edit distance

Implement `edit_distance(a, b)`: the minimum number of single-character
insertions, deletions, and substitutions needed to turn `a` into `b`
(Levenshtein distance).

Rules:

- identical strings return `0`;
- if one string is empty, the answer is the length of the other;
- swapping two adjacent characters costs `2` (two substitutions), not `1`: this
is not Damerau distance;
- case matters;
- each Unicode character counts as one character.

Example: `"kitten"` → `"sitting"` is `3`.

Use prefix DP: `d[i][j]` is the distance between the first `i` characters of `a`
and the first `j` characters of `b`. Two rows of the table are enough.

Python
algorithmsdynamic-programmingstrings
solution.py Python 3.14
AI mentor

The AI mentor is available after you log in: it sees your attempt history and does not spend resources on anonymous requests.

Log in and ask
Hints 1 of 3 unlocked · attempts: 0
Hint 1

What do the prefixes of the two strings have in common when the distances for
prefixes one character shorter are already known?

Hint 2 — unlocks after 1 attempt
Hint 3 — unlocks after 3 attempts