Minimum ASCII Delete Sum for Two Strings (LeetCode 712): Solution and Explanation

Medium
String
Dynamic Programming

Delete characters from two strings until they are equal, paying each deleted character's ASCII code. Find the cheapest total.

Intuition

Whatever survives in both strings is a common subsequence, and every other letter is paid for. So the goal is the common subsequence whose letters are worth the most, which is not always the longest one.

Look at the last letters of two prefixes. If they are equal, keep both for free and the cost is whatever the shorter prefixes needed. If they differ, one of them must be deleted: pay its ASCII code and take the cheaper of the two smaller problems.

Against an empty string every letter goes, so the first row and column are running sums of ASCII codes.

Approach: 2D DP over prefixes with ASCII weights

  1. Let dp[i][j] be the cheapest cost to make s1[:i] equal to s2[:j].
  2. Fill the borders: dp[i][0] = dp[i-1][0] + ord(s1[i-1]) and dp[0][j] = dp[0][j-1] + ord(s2[j-1]).
  3. If s1[i-1] == s2[j-1], set dp[i][j] = dp[i-1][j-1].
  4. Otherwise set dp[i][j] = min(dp[i-1][j] + ord(s1[i-1]), dp[i][j-1] + ord(s2[j-1])).
  5. Return dp[m][n].

Step-by-step example

s1 = "sea", s2 = "eat"
  1. Borders: column 0 is 0, 115, 216, 313 (s, e, a) and row 0 is 0, 101, 198, 314 (e, a, t).
  2. Row 's': 's' matches nothing, so each cell pays for a letter: dp[1][1] = min(101 + 115, 115 + 101) = 216, then 313 and 429.
  3. Row 'e': 'e' matches 'e', so dp[2][1] = dp[1][0] = 115. Then dp[2][2] = 115 + 97 = 212 and dp[2][3] = 212 + 116 = 328.
  4. Row 'a': 'a' matches 'a', so dp[3][2] = dp[2][1] = 115. Then dp[3][3] = min(328 + 97, 115 + 116) = 231.
  5. The answer is 231: delete 's' (115) and 't' (116), leaving "ea" in both strings.

Code: Python, Java, C++

1class Solution:
2    def minimumDeleteSum(self, s1: str, s2: str) -> int:
3        m, n = len(s1), len(s2)
4        dp = [[0] * (n + 1) for _ in range(m + 1)]
5        for i in range(1, m + 1):
6            dp[i][0] = dp[i - 1][0] + ord(s1[i - 1])
7        for j in range(1, n + 1):
8            dp[0][j] = dp[0][j - 1] + ord(s2[j - 1])
9        for i in range(1, m + 1):
10            for j in range(1, n + 1):
11                if s1[i - 1] == s2[j - 1]:
12                    dp[i][j] = dp[i - 1][j - 1]
13                else:
14                    dp[i][j] = min(dp[i - 1][j] + ord(s1[i - 1]), dp[i][j - 1] + ord(s2[j - 1]))
15        return dp[m][n]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(m * n)

Each of the (m + 1) x (n + 1) cells is filled once in constant time.

Space

O(m * n)

The full table is stored. Each row only reads the row above, so two rows of length n + 1 are enough.

Other approaches

Maximum-weight common subsequence (time O(m * n), space O(min(m, n)) with rolling rows)

Compute the largest ASCII sum of a common subsequence with an LCS-style DP that adds ord(c) on a match, then return the total ASCII of both strings minus twice that value.

Memoised recursion (time O(m * n), space O(m * n))

Recurse on (i, j) from the ends of the strings with the same rule and cache results. Same complexity, but deep recursion on 1000-letter inputs needs a raised recursion limit in Python.

Common mistakes

  • Maximising the length of the common subsequence is wrong here. In "delete" vs "leet", keeping "let" costs 403 while keeping "eet" costs 417, though both have length 3.
  • The borders are prefix sums, not plain indexes like in the unweighted delete problem.
  • On a mismatch, add the ASCII code of the letter you delete, not 1.

Frequently asked questions

How is this different from Delete Operation for Two Strings?

The recurrence has the same shape, but each deletion costs the letter's ASCII code instead of 1. That changes the borders to prefix sums and the mismatch case to adding ord of the deleted letter.

Why is keeping two equal last letters always safe?

If an optimal plan deleted one of two equal last letters, you could pair them and keep both, which removes a cost and adds none. So matching them never makes things worse.

Can the answer overflow a 32-bit integer?

No. At most 2000 letters are deleted and each costs at most 122, so the total stays under 250,000.

Can I use less memory?

Yes. Each row depends only on the row above and the cell to its left, so one array of length n + 1 plus a saved diagonal value is enough.