Skip to content

Edit distance

MediumPython 3Dynamic programmingStrings

You are given two strings a and b. Return the minimum number of single-
character operations needed to turn a into b, where an operation is one of:
  - insert a character
  - delete a character
  - replace a character

This is the classic Levenshtein distance, used in spell checkers and DNA sequence comparison.

Constraints:
  - 0 <= len(a), len(b) <= 1000
Examples:
  edit_distance("kitten", "sitting")     == 3   # replace k->s, e->i, insert g
  edit_distance("intention", "execution") == 5
  edit_distance("", "abc")               == 3   # three inserts
  edit_distance("abc", "abc")            == 0

Python 3, run in your browser. Run tests runs the problem's own tests with a free account; the AI interviewer reads your code and your runs in a practice interview.

Loading the editor…