Python coding

Fewest edits between two words

Return the smallest number of single-character edits that turn string a into string b. One edit inserts a character anywhere, deletes a character, or replaces a character with a different one.

Both strings have 0 to 60 characters, and uppercase and lowercase letters are different characters. Aim for O(len(a) · len(b)) time.

Besides the tests, one large input (9 and 10 letters, none shared) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • min_edits("trail", "rails") → 2
  • min_edits("lead", "gold") → 3
  • min_edits("", "tea") → 3
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Compare prefixes: let dp[i][j] be the fewest edits that turn a[:i] into b[:j]. The answer is dp[len(a)][len(b)].

Hint 2

If the last characters match, dp[i][j] = dp[i-1][j-1]. Otherwise take 1 plus the smallest of dp[i-1][j] (delete), dp[i][j-1] (insert) and dp[i-1][j-1] (replace).

Hint 3

The borders are not zero: dp[0][j] = j inserts and dp[i][0] = i deletes. And cell dp[i][j] compares a[i-1] with b[j-1], not a[i] with b[j].

Solution and why it works
pythonO(m·n), m = len(a), n = len(b) · O(n)
def min_edits(a: str, b: str) -> int:
    prev = list(range(len(b) + 1))       # row for a[:0]: building b[:j] takes j inserts
    for i, ca in enumerate(a, 1):
        cur = [i]                        # emptying a[:i] takes i deletes
        for j, cb in enumerate(b, 1):
            if ca == cb:
                cur.append(prev[j - 1])  # last characters match: nothing to pay
            else:                        # delete ca, insert cb, or replace ca with cb
                cur.append(1 + min(prev[j], cur[j - 1], prev[j - 1]))
        prev = cur
    return prev[-1]

Look at the last characters of the two prefixes. If they match, they cost nothing. If not, the last edit is a delete, an insert or a replace, and each leaves a smaller prefix pair: m × n states at O(1) each, keeping only the previous row. Traps: the borders are i and j, not 0, and cell (i, j) reads a[i-1]. Shortcuts through the longest common subsequence fail: "ab" → "ba" takes 2 edits, not 1.

Related lab: Big-O growth