CodeArchon

medium2-D Dynamic ProgrammingGoogleAmazon

Spell-Correction Minifier

A spell-check engine turns one word into another using the fewest single-character insert/delete/replace edits.

Given word1 and word2, return the minimum number of operations (insert, delete, replace) to convert word1 to word2.

Choose approach

0
1
2
3
1
1
2
3
row
2
?
?
?
3
?
?
?
4
?
?
?
5
?
?
?
1/6
Narrationstep 1 of 6

Row 1 (prefix "h") filled.

1def minDistance(a, b):
2 m, n = len(a), len(b)
3 dp = [[0]*(n+1) for _ in range(m+1)]
4 for i in range(m+1): dp[i][0] = i
5 for j in range(n+1): dp[0][j] = j
6 for i in range(1, m+1):
7 for j in range(1, n+1):
8 dp[i][j] = dp[i-1][j-1] if a[i-1] == b[j-1] else 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
9 return dp[m][n]
Variables
i=1

How to think about it

  1. Row 0 = inserts; column 0 = deletes.
  2. Diagonal when characters match.

Edge cases to catch in interview

  • Equal strings -> 0.
  • One empty -> length of the other.

Examples

Example 15
{"word1":"intention","word2":"execution"}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed