The rules for the puzzle are:
- Each triplet has the rules of how the letters are ordered in the secret word (each letter is followed by the next letter inside the triplet array).
- all the letters of the secret word are distinct.
Example input:
triplets1 = [
['t','u','p'],
['w','h','i'],
['t','s','u'],
['a','t','s'],
['h','a','p'],
['t','i','s'],
['w','h','s']
]
Expected Output: "whatisup"
I came up with this code, which works. It selects the first letters that are not preceded by any others in the arrays they are placed, removes them, concatenates them into the final word, and keep doing that until all the arrays are empty. The code isn't being accepted though, because is exceeding the time limit.
How can I optimize it or should I change the logic?
function recoverSecret(triplets) {
let secretWord = '', character = '';
let notEmpty = true;
let size = triplets.length;
//it loops until array is empty
while(notEmpty) {
notEmpty = false;
for (let i = 0; i < size; i++) {
for (let j = 0; j < triplets[i].length; j++) {
if (character) j = 0; //everytime a character is included, this condition is truthy, so you have to go back to the start of the array because the character was removed last iteration
character = triplets[i][j];
let remove = []; //this array will have the positions of the letter to remove in the removal cycle
for (let k = 0; k < size; k++) {
if (character == triplets[k][0]) remove.push(k);
//if the letter is in the triplet and it's not the first position, then it isn't the letter we're looking for, so character equals to '', otherwise it will be the letter which will be added to the secretWord string
if (k != i && (triplets[k].includes(character))) {
if (character != triplets[k][0]) {
character = '';
break;
}
}
}
secretWord += character;
if (character) {
//if character is not '', then a removal loop is done to remove the letter because we just found its place
for (x of remove) {
triplets[x].shift();
}
}
// if (triplets[i].length == 0) break;
}
if (triplets[i] != 0) notEmpty = true; //if every triplet is empty, notEmpty remains false and while loop is over
}
}
return secretWord;
}
link for the codewars problem (if needed): https://www.codewars.com/kata/53f40dff5f9d31b813000774