Minimum ASCII Delete Sum for Two Strings — LeetCode 712 Python Solution

MediumStringDynamic Programming
Problem
#712
Reading time
3 min

The problem

Given two strings s1 and s2, return the lowest ASCII sum of deleted characters to make two strings equal.

Example

Input
s1 = "sea", s2 = "eat"
Output
231
Explanation
Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum.

Python solution

Python
class Solution:
    def minimumDeleteSum(self, s1: str, s2: str) -> int:
        m, n = len(s1), len(s2)
        f = [[0] * (n + 1) for _ in range(m + 1)]
        for i in range(1, m + 1):
            f[i][0] = f[i - 1][0] + ord(s1[i - 1])
        for j in range(1, n + 1):
            f[0][j] = f[0][j - 1] + ord(s2[j - 1])
        for i in range(1, m + 1):
            for j in range(1, n + 1):
                if s1[i - 1] == s2[j - 1]:
                    f[i][j] = f[i - 1][j - 1]
                else:
                    f[i][j] = min(
                        f[i - 1][j] + ord(s1[i - 1]), f[i][j - 1] + ord(s2[j - 1])
                    )
        return f[m][n]

Complexity

MeasureComplexity
TimeO(m \times n)
SpaceO(m \times n) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 712. Minimum ASCII Delete Sum for Two Strings is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 712. Minimum ASCII Delete Sum for Two Strings?
LeetCode 712. Minimum ASCII Delete Sum for Two Strings is rated Medium on LeetCode.
What is the time complexity of LeetCode 712. Minimum ASCII Delete Sum for Two Strings?
The Python solution on this page runs in O(m \times n).
What is the space complexity of LeetCode 712. Minimum ASCII Delete Sum for Two Strings?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 712. Minimum ASCII Delete Sum for Two Strings cover?
LeetCode 712. Minimum ASCII Delete Sum for Two Strings is tagged String and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview