Music streaming app~25 min2s · 256 MBtarget O(n × m) time, O(m) spaceclassic twin: lc-583dp
A music streaming app stores a short tag for each track, a string of lowercase letters that encodes its mood and genre. A tool suggests that two tracks belong in one playlist when their tags can be made equal by deleting letters.
Deleting a letter from either tag costs one. You must find the fewest deletions, from both tags together, that make the two tags equal.
Write fewest_deletions(first, second).
first and second are tags, strings of lowercase letters.Input: first = "dancer", second = "danger"
Output: 2Let del[i][j] be the fewest deletions that make the first i letters of first equal to the first j letters of second. Making a prefix equal to nothing deletes all of it: del[i][0] = i and del[0][j] = j. When the next two letters are equal, keep both: del[i][j] = del[i - 1][j - 1]. Otherwise one of the two letters must go, and the cheaper choice is 1 + min(del[i - 1][j], del[i][j - 1]).
| first \ second | (none) | d | a | n | g | e | r |
|---|---|---|---|---|---|---|---|
| (none) | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
| d | 1 | 0 | 1 | 2 | 3 | 4 | 5 |
| a | 2 | 1 | 0 | 1 | 2 | 3 | 4 |
| n | 3 | 2 | 1 | 0 | 1 | 2 | 3 |
| c | 4 | 3 | 2 | 1 | 2 | 3 | 4 |
| e | 5 | 4 | 3 | 2 | 3 | 2 | 3 |
| r | 6 | 5 | 4 | 3 | 4 | 3 | 2 |
The last cell holds 2. Delete c from the first tag and g from the second, and both become daner.
Input: first = "cart", second = "cart"
Output: 0The tags are already equal.
Input: first = "abc", second = "xyz"
Output: 6No letter is shared, so every letter must be deleted, three from each tag.
1 ≤ len(first) ≤ 1000 and 1 ≤ len(second) ≤ 1000There are 1,001 × 1,001 = about a million pairs of prefix lengths, and each takes one step. The number of ways to delete letters from two tags of 1,000 letters is 2^2000, so trying every way is impossible.