Search~40 min2s · 256 MBtarget O(n × m) time, O(n × m) spaceclassic twin: lc-72dp
A search box has a command palette. A command is a list of words, such as deploy staging now. When someone types a command that does not exist, the palette suggests the closest one.
Closeness is the fewest edits of whole words. An edit inserts a word, deletes a word, replaces a word by another, or swaps two neighbouring words. People often type words in the wrong order, so a swap costs one edit and not two.
Write command_distance(first, second).
first and second are commands, lists of words made of lowercase letters. Either may be empty.first into second.Input: first = ["deploy", "staging", "now"], second = ["staging", "deploy", "later"]
Output: 2Let dist[i][j] be the fewest edits that turn the first i words of first into the first j words of second. The usual table uses a match, an insert, a delete and a replace. A swap adds a fifth move. If the last two words of one prefix are the last two of the other in the opposite order, the pair costs one edit.
| first \ second | (none) | staging | deploy | later |
|---|---|---|---|---|
| (none) | 0 | 1 | 2 | 3 |
| deploy | 1 | 1 | 1 | 2 |
| staging | 2 | 1 | 1 | 2 |
| now | 3 | 2 | 2 | 2 |
The last cell holds 2: swap deploy and staging, then replace now by later. Without the swap it would take 3 edits.
Input: first = ["gamma", "alpha"], second = ["alpha", "beta", "gamma"]
Output: 2Swap gamma and alpha, then insert beta between them. That is 2 edits, although the swapped pair is no longer next to each other in the end.
Input: first = ["restart", "web"], second = ["restart", "web"]
Output: 0The commands are equal, so no edit is needed.
0 ≤ len(first) ≤ 500 and 0 ≤ len(second) ≤ 500There are 501 × 501 = 251,001 pairs of prefix lengths, and each takes a few steps. The number of ways to edit one command into another is far larger, since each word offers four kinds of edit, so trying all sequences is impossible. A swap needs one extra look-up for each cell, which keeps the work near 251,001 steps.