#712
Minimum ASCII Delete Sum for Two Strings
MediumStringDynamic ProgrammingDynamic ProgrammingString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(m * n) |
| Space | O(1) | O(m * n) |
💡
Intuition
Time O(m * n)Space O(m * n)
The optimal approach uses dynamic programming to build a solution incrementally. We create a table that stores the minimum ASCII delete sum for substrings of s1 and s2, allowing us to avoid redundant calculations.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a 2D array dp where dp[i][j] represents the minimum ASCII delete sum for s1[0:i] and s2[0:j].
- 2Step 2: Fill the first row and first column of the dp array based on the ASCII values of characters in s1 and s2.
- 3Step 3: Iterate through the rest of the dp array, filling it based on whether the characters match or not, using previously computed values.
solution.py15 lines
1# Full working Python code
2def minimumDeleteSum(s1, s2):
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]ℹ
Complexity note: The time complexity is O(m * n) because we fill a 2D table of size m x n, where m and n are the lengths of the two strings. The space complexity is also O(m * n) due to the storage of this table.
- 1Dynamic programming allows us to break down the problem into smaller subproblems, making it easier to solve.
- 2Understanding the relationship between the characters of the two strings helps in optimizing the solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.