Problem
We are required to write a JavaScript function that takes in two strings of English lowercase alphabets, str1 and str2, as the first and the second argument respectively.
Our function is supposed to find and return the lowest ASCII sum of deleted characters to make two strings equal.
For example, if the input to the function is
Input
const str1 = 'sea'; const str2 = 'eat';
Output
const output = 231;
Output 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
Following is the code −
const str1 = 'sea'; const str2 = 'eat'; const minimumSum = (str1 = '', str2 = '') => { const chartCode = (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) { current[ind2] = chartCode(str2.slice(ind2)) } else if (ind2 === str2.length) { current[ind2] = chartCode(str1.slice(ind1)) } else if (str1[ind1] === str2[ind2]) { current[ind2] = prev[ind2 + 1] } else { current[ind2] = Math.min( prev[ind2] + (str1[ind1]).charCodeAt(0), current[ind2 + 1] + (str2[ind2]).charCodeAt(0), ) } } prev = current } return prev[0] } console.log(minimumSum(str1, str2));
Output
231