Edit Distance
hardLeetCode Top 100dynamic-programmingstrings
Problem
Given two strings, return the minimum number of single-character insertions, deletions, or substitutions needed to transform the first into the second.
Examples
Input: a = "horse", b = "ros"
Output: 3
Replace h, remove r, remove e.
Input: a = "intention", b = "execution"
Output: 5
Five edits convert one to the other.
Constraints
- • 0 <= a.length, b.length <= 500
- • Strings contain lowercase English letters
Hints(tap to reveal)
- 1. Compare prefixes of the two strings.
- 2. Matching characters cost nothing; otherwise take the cheapest of three edits.
Optimal approach(spoiler)
- Define dist(i, j) as the edit distance between the first i and first j characters.
- If the current characters match, carry the diagonal value.
- Otherwise take one plus the minimum of insert, delete, and replace neighbours.
- Fill the table row by row, base cases being empty prefixes.
- O(m * n) time, O(min(m, n)) space with a rolling row.
Ready to solve it?
Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.
Practice in the editor