◀ THE GRIND — 2-D DYNAMIC PROGRAMMING

Edit Distance

MEDIUM✓ CHIP-TIMEDLC #72 — FULL STATEMENT ↗

The drill: Find the fewest single-character insertions, deletions, and substitutions needed to turn one word into another.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

Two words show up, and the job is finding the smallest number of single-character edits — inserting a letter, deleting a letter, or swapping one letter for another — that turns the first word into the second.

Each edit touches exactly one character and counts as one step regardless of which of the three operations it is. Matching characters that already line up cost nothing and never need to be touched.

Either word can be empty, and letters may repeat freely within or across the two words — the only thing being measured is the shortest chain of edits that bridges them.

EX 01
word1 = "flower" · word2 = "flow"
2
THE BOARD'S EXAMPLE — TWO TRAILING DELETIONS
EX 02
word1 = "abcdef" · word2 = "azced"
3
EX 03
word1 = "" · word2 = ""
0
TWO EMPTY WORDS
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

Compare the two words from their last characters backward. If those two characters already match, that pair costs nothing — the problem reduces to the same question on both words with that character stripped off.

HINT 2 THE STRUCTURE

When the last characters differ, exactly one edit has to happen at that position — but which one? Try all three: delete from the first word, insert to match the second, or substitute it, and recurse on whichever leftover pair results.

HINT 3 ONE STEP FROM THE ANSWER

dp(i, j) = dp(i−1, j−1) when word1[i−1] == word2[j−1]; otherwise 1 + min(dp(i−1, j), dp(i, j−1), dp(i−1, j−1)) — deletion, insertion, substitution. Base cases: dp(i, 0) = i, dp(0, j) = j.

COACH'S BOARD — THE PATTERN, STEP BY STEP
THE EDIT LEDGERPATTERN · EDIT DISTANCE TABLEword1 = "ab" · word2 = "ba"
0
1
2
1
2
STEP 1

word1='ab', word2='ba'. Base cases: dp[0][j]=j inserts build word2's prefix from nothing; dp[i][0]=i deletes empty word1's prefix.

STEP 1 / 6 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/edit-distance.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        n, m = len(word1), len(word2)
        dp = [[0] * (m + 1) for _ in range(n + 1)]
        for i in range(n + 1):
            dp[i][0] = i
        for j in range(m + 1):
            dp[0][j] = j

        for i in range(1, n + 1):
            for j in range(1, m + 1):
                if word1[i - 1] == word2[j - 1]:
                    dp[i][j] = dp[i - 1][j - 1]
                else:
                    dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1])

        return dp[n][m]
TIME O(M·N)SPACE O(M·N)PYTHON · RACE PACE · 17 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED