InferenceAI

Enter at least two characters to search.

Start free

Edit Distance

hardDynamic Programming40 min50 XP

Return the minimum number of single-character insertions, deletions or substitutions needed to turn a into b (the Levenshtein distance).

D[i][j]={D[i−1][j−1]ai=bj1+min⁡(D[i−1][j], D[i][j−1], D[i−1][j−1])otherwiseD[i][j] = \begin{cases} D[i-1][j-1] & a_i = b_j \\ 1 + \min(D[i-1][j],\, D[i][j-1],\, D[i-1][j-1]) & \text{otherwise} \end{cases}

Examples

EXAMPLE WALKTHROUGHthree edits

A guided view of the published example, not a trace of your code.

INPUT["horse","ros"]
TASKedit_distance()
EXPECTED OUTPUT3

Start with the input values shown in this example.

Example 1 of 3

Input: a = "horse", b = "ros"

Output: 3

Explanation: three edits

Input: a = "intention", b = "execution"

Output: 5

Explanation: five edits

Input: a = "", b = "abc"

Output: 3

Explanation: from empty

Hint 1

D[i][0] = i and D[0][j] = j.

Hint 2

You only need two rows of the table at a time.

Topics

DSADynamic ProgrammingPython