Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Edit Distance

Dynamic Programminghard

Implement `editDistance(a, b)` returning the minimum number of single-character insertions, deletions, or substitutions needed to turn string `a` into string `b` (the Levenshtein distance).

Examples

Input: a = "horse", b = "ros"
Output: 3
horse → rorse → rose → ros.
Input: a = "intention", b = "execution"
Output: 5

Sample tests

Input: editDistance("horse", "ros")
Output: 3
Input: editDistance("intention", "execution")
Output: 5

+ 2 hidden tests run on Submit.

Hints

Common pitfalls
  • Forgetting to seed the first row and column (transforming to/from the empty string) breaks the recurrence.

Learning resources

  • Wikipedia: Edit distance
Approach & explanation (try first)

Classic two-dimensional DP. The base row/column encode turning a prefix into the empty string. Each cell either inherits the diagonal on a match or adds one operation to the cheapest neighbour. O(m × n) time and space.

Loading...
⌘/Ctrl + Enter

Run your code to see results.