DevPath

← All problems

Edit Distance

Hard dynamic-programming · strings

Description

Return the minimum number of single-character insertions, deletions or substitutions to change one word into another.

Constraints

0 <= lengths <= 500

Examples

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

Output: 3

Hints (1)
  • Compare prefixes; the answer is the minimum of three neighbouring cells.

Solutions

Rolling DP row. · Time O(n*m) · Space O(m)

func minDistance(a, b string) int {
    n, m := len(a), len(b)
    dp := make([]int, m+1)
    for j := 0; j <= m; j++ {
        dp[j] = j
    }
    for i := 1; i <= n; i++ {
        prev := dp[0]
        dp[0] = i
        for j := 1; j <= m; j++ {
            tmp := dp[j]
            cost := 1
            if a[i-1] == b[j-1] {
                cost = 0
            }
            dp[j] = min3(dp[j]+1, dp[j-1]+1, prev+cost)
            prev = tmp
        }
    }
    return dp[m]
}

func min3(a, b, c int) int {
    m := a
    if b < m {
        m = b
    }
    if c < m {
        m = c
    }
    return m
}

Create a free account to submit solutions, track progress and save problems.

Create account