Solving Two to One Codewars Problem in JS
The problem is about 2 strings to create a single string, all characters should be unique, and they should be sorted alphabetically in ascending order.
Problem: Take 2 strings s1 and s2 including only letters from a to z. Return a new sorted string (alphabetical ascending), the longest possible, containing distinct letters – each taken only once – coming from s1 or s2.
Examples:
a = "xyaabbbccccdefww"
b = "xxxxyyyyabklmopq"
longest(a, b) -> "abcdefklmopqwxy"
a = "abcdefghijklmnopqrstuvwxyz"
longest(a, a) -> "abcdefghijklmnopqrstuvwxyz"
In my mind, there are two ways to fix this problem:
- Use Object with keys of each characters of alphabet and check if string contains the character then store value true for that character in the object.
- Use Array of size all characters, but don’t store the character until they are present in the string. It would even result a sorted array.
Using Object
- Create an object with all character’s keys by default value should be false. Example: {a: false, b: false, …}
- Add/concatenate s1 and s2 strings to build a single string. Example (s3 = s1+s2)
- Split the string on empty character to make an array with each characters using this code: s3.split(“”)
- loop on s3Array for each characters and set true in object for the characters found.
- Create an empty array.
- Loop over the object keys and store the key in new array if the value is true.
- Join the new array to make string with this code: newArray.join(“”)
- Return the newString as answer.
function longest(s1, s2) {
const alphabetArray = Array.from({ length: 26 }, (_, i) => [String.fromCharCode(97+i), false])
const alphabetObject = Object.fromEntries(alphabetArray)
const s3 = s1+s2;
const s3Array = s3.split("");
s3Array.forEach(char => {
alphabetObject[char] = true;
})
let result = [];
Object.keys(alphabetObject).forEach(key => {
if(alphabetObject[key]) {
result.push(key);
}
})
return result.join("");
}
Using Array
- Create an empty array with 26 items space. Because alphabet do have 26 characters.
- Add/concat s1 and s2 strings to build a single string.
- Split the string on empty character to make an array with each characters using this code: s3.split(“”)
- loop on s3Array for each characters and for each character get their character code using this code: character.charCodeAt(0).
- Char Code will be from 97 (for character “a”) to 122 (for character “z”).
- Subtract 97 from the value of the character and store the character at the subtracted value index in array.
- Join the array on empty character to create a string.
function longest(s1, s2) {
const alphabetArray = new Array(26);
const s3 = s1+s2;
const s3Array = s3.split("");
s3Array.forEach(char => {
const charCode = char.charCodeAt(0);
alphabetArray[charCode-97] = char;
})
return alphabetArray.join("");
}
Link to problem: https://www.codewars.com/kata/5656b6906de340bd1b0000ac