Problem 712 · LeetCode 712(opens in a new tab)
Minimum ASCII Delete Sum for Two Strings
MediumDynamic programming
You are given two lower-case words, s1 and s2. You may delete any letters you like from either word, and each deleted letter costs its ASCII code (a = 97, b = 98, up to z = 122).
Return the smallest total cost that leaves the two words equal. Deleting everything is allowed: two empty words are equal.
Example 1
Input: s1 = "cab", s2 = "bad" Output: 393 Why: keep "b": delete c, a (99 + 97) and a, d (97 + 100)
2 more examples and the constraints
Example 2
Input: s1 = "pot", s2 = "top" Output: 446 Why: only one letter can be kept; keeping t, the costliest, saves most
Example 3
Input: s1 = "kite", s2 = "kite" Output: 0 Why: the words are already equal
Constraints
- 1 ≤ length of s1, length of s2 ≤ 1,000
- Both words use only the letters a to z
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursion with a memoO(m·n)
- Bottom-up tableO(m·n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for two 1,000-letter words | Verdict |
|---|---|---|---|
| Recursion with a memo | O(m·n) | Passes; recursion and hashing cost extra | |
| Bottom-up table | O(m·n) | Best; plain loops |
m and n = lengths of s1 and s2.
Edge cases to test
- Equal words. "kite" and "kite" cost 0.
- Nothing in common. "abc" and "xyz" delete every letter: 294 + 363 = 657.
- One word inside the other. "plan" and "planet": delete e and t, 101 + 116 = 217.
- Ties in length, not in cost. "cab" and "bad" can keep "a" or "b"; keeping "b" is cheaper.
- Single letters. "q" and "z" cost 113 + 122 = 235.
Common mistakes
- Counting deleted letters instead of adding their codes.
- Filling the first row and column with 0 instead of running sums of codes.
- Using the longest common subsequence by length, which can keep the wrong letters.
How to talk through it
- 1Clarify. What does a letter cost? May both words be emptied? Only lower-case letters?
- 2Give the recursion. Compare front letters: keep a match, else try deleting either side. Add a memo.
- 3Define the table. dp[i][j] is the cost for the first i and j letters; edges are running sums.
- 4Code it bottom-up. Copy the diagonal on a match, else take the cheaper of up and left plus a code.
- 5Test out loud. Run equal words, disjoint words and the "cab" / "bad" tie before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?