Problem Description
Given two strings s1 and s2, return the lowest ASCII sum of deleted characters to make two strings equal.
Key Insights
- The goal is to make two strings equal by deleting characters.
- The ASCII values of the characters that are deleted contribute to the total sum.
- A dynamic programming approach can be used to efficiently calculate the minimum sum of deleted ASCII values.
- The problem can be viewed as finding the longest common subsequence (LCS), where the characters not in the LCS are the ones that need to be deleted.
Space and Time Complexity
Time Complexity: O(m * n), where m is the length of s1 and n is the length of s2.
Space Complexity: O(m * n) for the dynamic programming table.
Solution
We can solve this problem using dynamic programming. We will create a 2D array, dp
, where dp[i][j]
will store the minimum ASCII delete sum needed to make the first i characters of s1 and the first j characters of s2 equal.
- Initialize the
dp
array with size (m+1) x (n+1), where m and n are the lengths of s1 and s2, respectively. - Fill the first row and first column to represent the cost of deleting characters from either string.
- Iterate through each character pair from both strings:
- If the characters match, carry forward the previous cost (no deletion needed).
- If they don't match, calculate the cost of deleting either character and take the minimum.
- The final answer will be found in
dp[m][n]
.