Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Minimum ASCII Delete Sum for Two Strings

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "712" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

Given two strings s1 and s2, return the lowest ASCII sum of deleted characters to make two strings equal. Example 1: 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. Example 2: 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. If instead we turned both strings into "lee" or "eet", we would get answers of 433 or 417, which are higher. Constraints: 1 <= s1.length, s2.length <= 1000 s1 and s2 consist of lowercase English letters.

Explanation

Here's the breakdown of the solution:

  • Dynamic Programming: We use dynamic programming to build a table where dp[i][j] stores the minimum ASCII sum of deleted characters to make s1[0...i-1] and s2[0...j-1] equal.
  • Base Cases: dp[0][j] and dp[i][0] are initialized by accumulating the ASCII values of the characters in s2 and s1 respectively.
  • Recursive Relation: If s1[i-1] and s2[j-1] are equal, no deletion is needed. Otherwise, we consider two possibilities: delete s1[i-1] or delete s2[j-1], and choose the option that yields the minimum ASCII sum.

  • Time Complexity: O(m*n), where m and n are the lengths of s1 and s2, respectively. Space Complexity: O(m*n)

Code

    def minimumDeleteSum(s1: str, s2: str) -> int:
    """
    Given two strings s1 and s2, return the lowest ASCII sum of deleted characters to make two strings equal.
    """
    m, n = len(s1), len(s2)
    dp = [[0] * (n + 1) for _ in range(m + 1)]

    # Initialize base cases
    for j in range(1, n + 1):
        dp[0][j] = dp[0][j - 1] + ord(s2[j - 1])
    for i in range(1, m + 1):
        dp[i][0] = dp[i - 1][0] + ord(s1[i - 1])

    # Fill the dp table
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if s1[i - 1] == s2[j - 1]:
                dp[i][j] = dp[i - 1][j - 1]
            else:
                dp[i][j] = min(dp[i - 1][j] + ord(s1[i - 1]), dp[i][j - 1] + ord(s2[j - 1]))

    return dp[m][n]

More from this blog

C

Chatmagic blog

2894 posts