Search~30 min2s · 256 MBtarget O(n × m) time, O(m) spaceclassic twin: lc-72dp
A store's search box handles page addresses called slugs: lowercase words such as summer-sale, with the dashes removed here. When someone follows an old slug that no longer exists, the app suggests the page whose slug is closest.
Closeness is the fewest single-letter edits that turn one slug into the other. An edit inserts one letter, deletes one letter, or replaces one letter by another.
Write edit_distance(source, target).
source and target are slugs, strings of lowercase letters.source into target.Input: source = "sunday", target = "saturday"
Output: 3Let dist[i][j] be the fewest edits that turn the first i letters of source into the first j of target. Turning nothing into j letters takes j insertions, and i letters into nothing takes i deletions.
Equal next letters need no edit: dist[i][j] = dist[i - 1][j - 1]. Otherwise one edit is needed. Use the cheapest of a replace (the diagonal cell), a delete (the cell above) and an insert (the cell to the left): dist[i][j] = 1 + min(...).
| source \ target | (none) | s | a | t | u | r | d | a | y |
|---|---|---|---|---|---|---|---|---|---|
| (none) | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| s | 1 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| u | 2 | 1 | 1 | 2 | 2 | 3 | 4 | 5 | 6 |
| n | 3 | 2 | 2 | 2 | 3 | 3 | 4 | 5 | 6 |
| d | 4 | 3 | 3 | 3 | 3 | 4 | 3 | 4 | 5 |
| a | 5 | 4 | 3 | 4 | 4 | 4 | 4 | 3 | 4 |
| y | 6 | 5 | 4 | 4 | 5 | 5 | 5 | 4 | 3 |
The last cell holds 3. Insert a, insert t, and replace n by r.
Input: source = "cart", target = "cart"
Output: 0The slugs are equal, so no edit is needed.
Input: source = "abc", target = "xyz"
Output: 3No letter is shared, so each of the three letters is replaced.
1 ≤ len(source) ≤ 1000 and 1 ≤ len(target) ≤ 1000There are 1,001 × 1,001 = about a million pairs of prefix lengths, and each takes one step. The number of ways to edit one slug into another is far larger. Each letter offers three kinds of edit, so trying every sequence is impossible.