KatInterview

712. Minimum ASCII Delete Sum for Two Strings

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the minimum sum of ASCII values of characters that need to be deleted from two strings, s1 and s2, to make them identical. This problem can be rephrased as finding a common subsequence of s1 and s2 that has the maximum possible sum of ASCII values. If we maximize the sum of characters we keep (the common subsequence), we consequently minimize the sum of characters we delete. The total deletion cost would be the sum of ASCII values of all characters in s1 and s2 minus twice the sum of ASCII values of this maximum-sum common subsequence.

Solution

Minimum ASCII Delete Sum for Two Strings in Python

class Solution:
    def minimumDeleteSum(self, s1: str, s2: str) -> int:
        m, n = len(s1), len(s2)
        
        # dp array for space optimization, storing one row of the DP table.
        # dp[j] corresponds to the cost for s1's prefix and s2's prefix of length j.
        dp = [0] * (n + 1)
        
        # Initialize the first row (corresponding to an empty s1).
        # To make s2's prefix equal to an empty string, delete all its characters.
        for j in range(1, n + 1):
            dp[j] = dp[j-1] + ord(s2[j-1])
            
        # Iterate through s1 to build up the DP table row by row.
        for i in range(1, m + 1):
            # prev_row_val stores dp[i-1][j-1]
            prev_row_val = dp[0]
            # Update dp[0] for the current row i (dp[i][0]).
            # This means matching s1's prefix of length i with an empty s2.
            dp[0] += ord(s1[i-1])
            
            for j in range(1, n + 1):
                # temp stores dp[i-1][j]
                temp = dp[j]
                if s1[i-1] == s2[j-1]:
                    # Characters match, no deletion cost here.
                    # Cost is inherited from dp[i-1][j-1], which is prev_row_val.
                    dp[j] = prev_row_val
                else:
                    # Characters don't match, take the minimum of two deletion options:
                    # 1. Delete s1[i-1]: Cost is dp[i-1][j] (temp) + ord(s1[i-1])
                    # 2. Delete s2[j-1]: Cost is dp[i][j-1] (new dp[j-1]) + ord(s2[j-1])
                    dp[j] = min(temp + ord(s1[i-1]), dp[j-1] + ord(s2[j-1]))
                # Update prev_row_val for the next column.
                prev_row_val = temp
        
        return dp[n]

Minimum ASCII Delete Sum for Two Strings in Java

class Solution {
    public int minimumDeleteSum(String s1, String s2) {
        int m = s1.length();
        int n = s2.length();

        // dp[j] will store the minimum delete sum for s1's prefix up to i-1 and s2's prefix up to j-1.
        // This is a space-optimized DP approach using O(n) space.
        int[] dp = new int[n + 1];

        // Initialize the first row (corresponding to an empty s1).
        // To make s2's prefix equal to an empty string, we must delete all characters of s2's prefix.
        for (int j = 1; j <= n; j++) {
            dp[j] = dp[j - 1] + s2.charAt(j - 1);
        }

        // Fill DP table row by row for each character in s1.
        for (int i = 1; i <= m; i++) {
            // prev_row_val stores dp[i-1][j-1]
            int prev_row_val = dp[0];
            // Update dp[0] for the current row i, which is dp[i][0].
            // This means matching s1's prefix of length i with an empty string s2.
            dp[0] += s1.charAt(i - 1);

            for (int j = 1; j <= n; j++) {
                // temp stores dp[i-1][j]
                int temp = dp[j]; 
                if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
                    // Characters match, no deletion needed at this step.
                    // The cost is inherited from dp[i-1][j-1], which is prev_row_val.
                    dp[j] = prev_row_val;
                } else {
                    // Characters differ, take the minimum of two deletion choices:
                    // 1. Delete s1.charAt(i-1): cost is dp[i-1][j] (temp) + ascii(s1[i-1])
                    // 2. Delete s2.charAt(j-1): cost is dp[i][j-1] (the new dp[j-1]) + ascii(s2[j-1])
                    dp[j] = Math.min(temp + s1.charAt(i - 1), dp[j - 1] + s2.charAt(j - 1));
                }
                // Update prev_row_val for the next iteration of j.
                prev_row_val = temp;
            }
        }

        return dp[n];
    }
}

Minimum ASCII Delete Sum for Two Strings in C++

class Solution {
public:
    int minimumDeleteSum(string s1, string s2) {
        int m = s1.length();
        int n = s2.length();

        // dp[j] will store the minimum delete sum for s1's prefix up to i-1 and s2's prefix up to j-1.
        // This is a space-optimized DP approach using O(n) space.
        vector<int> dp(n + 1, 0);

        // Initialize the first row (corresponding to an empty s1).
        // To make s2's prefix equal to an empty string, we must delete all characters of s2's prefix.
        for (int j = 1; j <= n; ++j) {
            dp[j] = dp[j - 1] + s2[j - 1];
        }

        // Fill DP table row by row for each character in s1.
        for (int i = 1; i <= m; ++i) {
            // prev_row_val stores dp[i-1][j-1]
            int prev_row_val = dp[0];
            // Update dp[0] for the current row i, which is dp[i][0].
            // This means matching s1's prefix of length i with an empty string s2.
            dp[0] += s1[i - 1];

            for (int j = 1; j <= n; ++j) {
                // temp stores dp[i-1][j]
                int temp = dp[j]; 
                if (s1[i - 1] == s2[j - 1]) {
                    // Characters match, no deletion needed at this step.
                    // The cost is inherited from dp[i-1][j-1], which is prev_row_val.
                    dp[j] = prev_row_val;
                } else {
                    // Characters differ, take the minimum of two deletion choices:
                    // 1. Delete s1[i-1]: cost is dp[i-1][j] (temp) + ascii(s1[i-1])
                    // 2. Delete s2[j-1]: cost is dp[i][j-1] (the new dp[j-1]) + ascii(s2[j-1])
                    dp[j] = min(temp + s1[i - 1], dp[j - 1] + s2[j - 1]);
                }
                // Update prev_row_val for the next iteration of j.
                prev_row_val = temp;
            }
        }

        return dp[n];
    }
};

Minimum ASCII Delete Sum for Two Strings in TypeScript

function minimumDeleteSum(s1: string, s2: string): number {
    const m = s1.length;
    const n = s2.length;

    // dp array for space optimization, storing one row of the DP table.
    // dp[j] corresponds to the cost for s1's prefix and s2's prefix of length j.
    let dp: number[] = new Array(n + 1).fill(0);

    // Initialize the first row (corresponding to an empty s1).
    // To make s2's prefix equal to an empty string, delete all its characters.
    for (let j = 1; j <= n; j++) {
        dp[j] = dp[j - 1] + s2.charCodeAt(j - 1);
    }

    // Iterate through s1 to build up the DP table row by row.
    for (let i = 1; i <= m; i++) {
        // prev_row_val stores dp[i-1][j-1]
        let prev_row_val = dp[0];
        // Update dp[0] for the current row i (dp[i][0]).
        // This means matching s1's prefix of length i with an empty s2.
        dp[0] += s1.charCodeAt(i - 1);

        for (let j = 1; j <= n; j++) {
            // temp stores dp[i-1][j]
            const temp = dp[j];
            if (s1.charCodeAt(i - 1) === s2.charCodeAt(j - 1)) {
                // Characters match, no deletion cost here.
                // Cost is inherited from dp[i-1][j-1], which is prev_row_val.
                dp[j] = prev_row_val;
            } else {
                // Characters don't match, take the minimum of two deletion options:
                // 1. Delete s1[i-1]: Cost is dp[i-1][j] (temp) + ascii(s1[i-1])
                // 2. Delete s2[j-1]: Cost is dp[i][j-1] (new dp[j-1]) + ascii(s2[j-1])
                dp[j] = Math.min(temp + s1.charCodeAt(i - 1), dp[j - 1] + s2.charCodeAt(j - 1));
            }
            // Update prev_row_val for the next column.
            prev_row_val = temp;
        }
    }

    return dp[n];
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.