Python 0712.py
class Solution:
def minimumDeleteSum(self, s1: str, s2: str) -> int:
# modified edit distance
dp = []
for _ in range(len(s1) + 1):
dp.append([0] * (len(s2) + 1))
for i in range(len(s1) - 1, -1, -1):
dp[i][len(s2)] = ord(s1[i]) + dp[i+1][len(s2)]
for j in range(len(s2) - 1, -1, -1):
dp[len(s1)][j] = ord(s2[j]) + dp[len(s1)][j+1]
for i in range(len(s1) - 1, -1, -1):
for j in range(len(s2) - 1, -1, -1):
if s1[i] == s2[j]:
dp[i][j] = dp[i+1][j+1]
else:
one = ord(s1[i])
two = ord(s2[j])
dp[i][j] = min(one + dp[i+1][j], two + dp[i][j+1], one + two + dp[i+1][j+1])
return dp[0][0]
Difficulty
and has an acceptance rate of about 71% (300k+ submissions).
Typical patterns to solve this problem:
- Dynamic Programming
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the “minimum ASCII delete sum for two strings” problem by constructing a dynamic-programming table that records the cheapest cost to make the suffixes of the two input strings equal. The algorithm proceeds in a bottom-up fashion, filling the table from the ends of the strings toward the beginning, and finally returns the value stored at the top-left cell, which represents the minimum total ASCII value of characters that must be deleted from the original strings.
DP Table Allocation
The first step creates a two-dimensional list dp whose dimensions are (len(s1) + 1) × (len(s2) + 1). Each cell is initialized to zero, establishing a clean slate for subsequent calculations.
dp = []
for _ in range(len(s1) + 1):
dp.append([0] * (len(s2) + 1))
Base Cases for the Last Row and Column
The algorithm populates the last column of the table with the cumulative ASCII cost of deleting the remaining characters of s1 when s2 is already exhausted. A symmetric operation fills the last row with the cost of deleting the remaining characters of s2 when s1 is exhausted. These base cases anchor the recursion and guarantee that every subsequent cell has a well-defined predecessor.
for i in range(len(s1) - 1, -1, -1):
dp[i][len(s2)] = ord(s1[i]) + dp[i+1][len(s2)]
for j in range(len(s2) - 1, -1, -1):
dp[len(s1)][j] = ord(s2[j]) + dp[len(s1)][j+1]
Core DP Transition
The nested loops iterate backward over both strings. For each pair of positions (i, j), the algorithm distinguishes two scenarios:
-
When the characters match (
s1[i] == s2[j]), no deletion is required, and the cost equals the value already computed for the next pair of suffixes (dp[i+1][j+1]). -
When the characters differ, three deletion strategies are considered:
- Delete
s1[i]only. - Delete
s2[j]only. - Delete both characters simultaneously.
- Delete
The minimum of these three possibilities becomes the value for dp[i][j].
for i in range(len(s1) - 1, -1, -1):
for j in range(len(s2) - 1, -1, -1):
if s1[i] == s2[j]:
dp[i][j] = dp[i+1][j+1]
else:
one = ord(s1[i])
two = ord(s2[j])
dp[i][j] = min(
one + dp[i+1][j],
two + dp[i][j+1],
one + two + dp[i+1][j+1]
)
Result Extraction
After the table is fully populated, the entry at the top-left corner (dp[0][0]) holds the minimum total ASCII deletion cost for the original strings. The method returns this value directly.
return dp[0][0]
Edge Cases Handled
The implementation gracefully manages several boundary conditions:
-
When either input string is empty, the base-case loops fill the corresponding row or column with the total ASCII sum of the non-empty string, resulting in the correct total deletion cost.
-
Identical strings of any length trigger the equality branch throughout the DP fill, leading to a final cost of zero without unnecessary computation.
-
Strings containing characters with high ASCII codes (e.g., extended Latin or control characters) are correctly accounted for because the algorithm uses
ordto obtain the exact numeric value of each character. -
Different length strings are accommodated by the rectangular DP table, ensuring that every possible suffix pairing is evaluated.
Performance Optimizations Observed
The code exhibits several deliberate choices that improve runtime efficiency:
-
Pre-allocating the entire DP matrix avoids repeated list resizing during the fill phase, which reduces overhead associated with dynamic memory allocation.
-
The bottom-up traversal eliminates the need for recursion and associated call-stack management, providing a predictable execution pattern.
-
Direct use of
ordto compute character costs avoids any intermediate string manipulation, keeping the inner loop lightweight. -
The three-option
mincall consolidates the decision logic into a single expression, allowing the interpreter to evaluate the alternatives efficiently without extra branching structures.
These characteristics collectively enable the solution to process input strings of moderate length with a consistent and swift execution profile.
ELI5 - Simplified Explanation
Imagine you have two bags filled with colorful letter blocks. You want to make the bags match perfectly so they contain the exact same letters in the same order, but you have to throw away some blocks to make that happen. The goal is to make sure the total value of the blocks you throw away is kept as small as possible. Each block has a special secret number assigned to it.
First, a big empty grid is created to keep track of all the different ways to choose which blocks to keep and which to throw away. Think of this grid like a giant map that helps organize the best choices.
The computer looks at the very end of both bags and works backward. If the letters on the blocks match, they can stay together, and there is no need to throw anything away. But if they do not match, the computer calculates the cost of throwing away a block from the first bag or throwing away a block from the second bag. It compares these costs and picks the smallest one so that the smallest possible total value is tossed out.
By the time the computer finishes checking every single block against the others, it reaches the very start of the bags. The grid holds the answer to the smallest total value of the blocks that had to be removed.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Java | |||||||
| leetcode.ca | C++ | JS | Rust | Python | Java | Go | TS | ||
| LeetcodeHelp | C++ | Python | Java | ||||||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| withaarzoo | C++ | ||||||||
| zfang399 | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Java | ||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| withaarzoo | C++ | ||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 72: Edit Distance
- problem 300: Longest Increasing Subsequence
- problem 583: Delete Operation for Two Strings
Solved On The Same Day
- problem 71: Simplify Path
- problem 309: Best Time to Buy and Sell Stock with Cooldown
- problem 516: Longest Palindromic Subsequence
- problem 673: Number of Longest Increasing Subsequence
- problem 714: Best Time to Buy and Sell Stock with Transaction Fee
- problem 740: Delete and Earn
- problem 931: Minimum Falling Path Sum
- problem 2483: Minimum Penalty for a Shop
- problem 188: Best Time to Buy and Sell Stock IV
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality