Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Minimum deletion sum of characters in JavaScript
The minimum deletion sum problem requires finding the lowest ASCII sum of characters that need to be deleted from two strings to make them equal. This is solved using dynamic programming to find the optimal sequence of deletions.
Problem Statement
Given two strings of lowercase English letters, we need to delete characters from both strings to make them identical, while minimizing the sum of ASCII values of deleted characters.
Algorithm Approach
We use dynamic programming where each cell dp[i][j] represents the minimum deletion cost to make substrings str1[i:] and str2[j:] equal.
Example
Input:
str1 = 'sea' str2 = 'eat'
Process:
- Delete 's' from "sea" ? ASCII value 115
- Delete 't' from "eat" ? ASCII value 116
- Result: "ea" = "ea", total cost = 115 + 116 = 231
Implementation
const str1 = 'sea';
const str2 = 'eat';
const minimumSum = (str1 = '', str2 = '') => {
// Helper function to calculate ASCII sum of a string
const charCode = (s = '') => {
let code = 0;
for (const c of s) {
code += c.charCodeAt(0);
}
return code;
};
let prev = new Array(str2.length + 1).fill(0);
for (let ind1 = str1.length; ind1 >= 0; ind1--) {
const current = new Array(str2.length + 1).fill(0);
for (let ind2 = str2.length; ind2 >= 0; ind2--) {
if (ind1 === str1.length) {
// Delete all remaining characters from str2
current[ind2] = charCode(str2.slice(ind2));
} else if (ind2 === str2.length) {
// Delete all remaining characters from str1
current[ind2] = charCode(str1.slice(ind1));
} else if (str1[ind1] === str2[ind2]) {
// Characters match, no deletion needed
current[ind2] = prev[ind2 + 1];
} else {
// Choose minimum cost: delete from str1 or str2
current[ind2] = Math.min(
prev[ind2] + str1[ind1].charCodeAt(0), // Delete from str1
current[ind2 + 1] + str2[ind2].charCodeAt(0) // Delete from str2
);
}
}
prev = current;
}
return prev[0];
};
console.log(minimumSum(str1, str2));
231
How It Works
The algorithm works backwards through both strings:
- Base cases: If one string is exhausted, delete all remaining characters from the other
- Match: If characters match, move to next position without deletion cost
- No match: Choose the minimum cost between deleting from either string
Time Complexity
Time complexity: O(m × n) where m and n are the lengths of the input strings. Space complexity: O(n) using space optimization.
Conclusion
This dynamic programming solution efficiently finds the minimum ASCII deletion sum by considering all possible deletion combinations. The space-optimized approach reduces memory usage while maintaining optimal time complexity.
