Algorithms · Visualized
DP: Edit Distance
Dynamic Programming
Break problems into overlapping subproblems and store answers.
Finds the minimum number of single-character insertions, deletions, or substitutions needed to transform one string into another. Time: O(n × m) average, O(n × m) worst; space: O(n × m), reducible to O(min(n,m)).
Big-O: The most-asked interview category — 35 classics here.
Edit Distance (Levenshtein Distance)
Dynamic ProgrammingFinds the minimum number of single-character insertions, deletions, or substitutions needed to transform one string into another. dp[i][j] represents the edit distance between the first i characters of one string and the first j characters of the other, built by considering the cheapest of the three possible edit operations at each step.
How Edit Distance Works
- Create a DP table with dimensions (len1+1) × (len2+1). Initialize dp[i][0] = i (deleting all i characters) and dp[0][j] = j (inserting all j characters) as base cases.
- For each pair of positions (i, j), check if the characters at string1[i-1] and string2[j-1] match.
- If they match, no edit is needed for this character: dp[i][j] = dp[i-1][j-1] (carry forward the cost without these characters).
- If they don't match, consider the three possible operations: insert (dp[i][j-1] + 1), delete (dp[i-1][j] + 1), or substitute (dp[i-1][j-1] + 1) — take the minimum of these three.
- Continue filling the table; dp[len1][len2] holds the minimum edit distance.
Edit Distance Worked Example
Input: {word1: horse, word2: ros}
Building the table comparing 'horse' and 'ros': characters 'r','o','s' need to align, requiring deletion of 'h', substitution of 'r' for 'o'... working through the full table, the minimum edit distance to transform 'horse' into 'ros' comes out to 3 (e.g. delete 'h', substitute 'r'→'r' [match], delete 'o' or similar sequence of 3 operations).
| · | r | o | s | |
|---|---|---|---|---|
| · | 0 | 1 | 2 | 3 |
| h | 1 | 0 | 0 | 0 |
| o | 2 | 0 | 0 | 0 |
| r | 3 | 0 | 0 | 0 |
| s | 4 | 0 | 0 | 0 |
| e | 5 | 0 | 0 | 0 |
def edit_distance(a, b):
n, m = len(a), len(b)
prev = list(range(m + 1))
for i in range(1, n + 1):
cur = [i] + [0] * m
for j in range(1, m + 1):
if a[i - 1] == b[j - 1]:
cur[j] = prev[j - 1]
else:
cur[j] = 1 + min(prev[j], cur[j - 1], prev[j - 1])
prev = cur
return prev[m]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Edit Distance Time & Space Complexity
When to Use Edit Distance
- Spell checkers (suggesting corrections based on closest edit distance), DNA sequence alignment, and fuzzy string matching/search.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.