This content originally appeared on DEV Community and was authored by Nicolás Bost
Salutations.
I'm posting Codewars challenges and my thought process in this series. I'm using JS and Node 18 whenever possible. Just for the sake of clarity, I'm making fair use of them.
Ok, this was juicy. In essence, you have to remove duplicates in a string, order what's left and join two strings. Not exactly in that order. Actually, I did it in the exact opposite way. And I also built an utility function for a very specific step (removing duplicates).
First, concatenate two strings. Easy:
let longest = s1 + s2;
Second, split up the letters:
let array = new Array(s1.length + s2.length);
for (let i = 0 ; i < s1.length + s2.length ; i++ ){
array[i] = longest[i];
}
Third, sort the letters:
array = array.sort((a, b) => a.localeCompare(b));
// (a, b) => a.localeCompare(b) THIS IS REDUNDANT, but I leave it as a reminder
Fourth, remove duplicates:
function keepFirstLetter(array){
let arrayFixed = new Array(array.length);
let counter = 0;
arrayFixed[0] = array[0];
for (let i = 0 ; i < array.length ; i++ ){
if (arrayFixed[counter] != array[i]){
counter++;
arrayFixed[counter] = array[i];
}
}
return arrayFixed;
}
Fifth, clean up:
array = array.join("");
Last, place every piece of the puzzle together:
function longest(s1, s2) {
let array = new Array(s1.length + s2.length);
let longest = s1 + s2;
for (let i = 0 ; i < s1.length + s2.length ; i++ ){
array[i] = longest[i];
}
array = array.sort((a, b) => a.localeCompare(b));
array = keepFirstLetter(array);
array = array.join("")
return array;
}
function keepFirstLetter(array){
let arrayFixed = new Array(array.length);
let counter = 0;
arrayFixed[0] = array[0];
for (let i = 0 ; i < array.length ; i++ ){
if (arrayFixed[counter] != array[i]){
counter++;
arrayFixed[counter] = array[i];
}
}
return arrayFixed;
}
It's definitely NOT performant. I don't like that second loop. And it's not so clean either. Someday I'll need to revisit this one.
Be well. Drink water 💧💧💧.
This content originally appeared on DEV Community and was authored by Nicolás Bost
Nicolás Bost | Sciencx (2025-01-05T23:05:43+00:00) Codewars – Two to One. Retrieved from https://www.scien.cx/2025/01/05/codewars-two-to-one/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.
