Problem
We are required to write a JavaScript function that takes in two strings s1 and s2 including only letters from ato z.
Our function should return a new sorted string, the longest possible, containing distinct letters - each taken only once - coming from s1 or s2.
Example
Following is the code −
const str1 = "xyaabbbccccdefww";
const str2 = "xxxxyyyyabklmopq";
const longestPossible = (str1 = '', str2 = '') => {
const combined = str1.concat(str2);
const lower = combined.toLowerCase();
const split =lower.split('');
const sorted = split.sort();
const res = [];
for(const el of sorted){
if(!res.includes(el)){
res.push(el)
}
}
return (res.join(''));
};
console.log(longestPossible(str1, str2));Output
Following is the console output −
abcdefklmopqwxy