Problem
Given two stringss1 and s2, return the lowest ASCII sum of deleted characters to make two strings equal.
Examples
Constraints
- 1 <= s1.length, s2.length <= 1000
- s1 and s2 consist of lowercase English letters.
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 712 with 20 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 712 # by problem number
lcpy gen -s minimum_ascii_delete_sum_for_two_strings # by problem name
s1 and s2, return the lowest ASCII sum of deleted characters to make two strings equal.
Input: s1 = "sea", s2 = "eat"
Output: 231
Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum.
Deleting "t" from "eat" adds 116 to the sum.
At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.
Input: s1 = "delete", s2 = "leet"
Output: 403
Explanation: Deleting "dee" from "delete" to turn the string into "let", adds 100[d] + 101[e] + 101[e] to the sum.
Deleting "e" from "leet" adds 101[e] to the sum.
At the end, both strings are equal to "let", and the answer is 100 + 101 + 101 + 101 = 403.
class Solution:
# Time: O(m * n)
# Space: O(min(m, n))
def minimum_delete_sum(self, s1: str, s2: str) -> int:
if len(s1) < len(s2):
s1, s2 = s2, s1
prev = [0] * (len(s2) + 1)
for j in range(1, len(s2) + 1):
prev[j] = prev[j - 1] + ord(s2[j - 1])
for i in range(1, len(s1) + 1):
curr = [prev[0] + ord(s1[i - 1])]
for j in range(1, len(s2) + 1):
if s1[i - 1] == s2[j - 1]:
curr.append(prev[j - 1])
else:
curr.append(min(prev[j] + ord(s1[i - 1]), curr[j - 1] + ord(s2[j - 1])))
prev = curr
return prev[-1]
| Time | Space |
|---|---|
| O(m * n) | O(min(m, n)) |