Problem Description
Given two strings s1 and s2, the goal is to delete characters from both strings to make them equal while minimizing the total cost. The cost is the sum of the ASCII values of the characters deleted.
Key Insights
- Use dynamic programming to systematically compare characters of both strings.
- Define a state dp[i][j] representing the minimum deletion cost for the substrings s1[i:] and s2[j:].
- If s1[i] equals s2[j], no cost is incurred and we move diagonally.
- If the characters differ, decide between deleting s1[i] or s2[j] and take the minimum cost.
- Base cases handle situations where one string is empty by summing the ASCII values of the remaining characters in the other string.
Space and Time Complexity
Time Complexity: O(n * m), where n and m are the lengths of s1 and s2. Space Complexity: O(n * m), due to the DP table used to store intermediate results.
Solution
We build a 2D DP table where dp[i][j] is the minimum ASCII deletion sum required for making the substrings s1[i:] and s2[j:] equal. Starting from the end of the strings, if characters match then carry over the cost from dp[i+1][j+1]. Otherwise, consider the cost of deleting the current character from s1 or s2, and update dp[i][j] accordingly with the minimum of these two possibilities. The final answer is stored in dp[0][0].