I was solving the algorithm question and realized that the code passed all the test cases, excluding the efficiency of the code. Initially, I used 2 'for loops' but soon found that the time complexity of 2 'for loops' would consume too much time, which makes the efficiency of the code bad. Thus, changed the code like this.
Q) All runners passed the marathon excluding only one marathoner. Write the code that returns a certain runner who did not complete the marathon. Here are the expected outputs.
function solution(participant, completion) {
var sorted_index;
for (let i=0; i<completion.length; i ){
sorted_index = participant.indexOf(completion[i]);
answer = participant.splice(sorted_index, 1);
}
return participant.toString();
}
Can I get any ideas about what makes the code inefficient and get any alternatives? Thanks.
CodePudding user response:
An alternative solution is utilizing Array.prototype
methods, which are equipped so solve this kind of problem easily.
You can use Array.prototype.find
which finds only the first occurence. It also handles duplicates like in the last case by removing any checked names.
function solution(participant, completion) {
return participant.find((person) => {
if (completion.includes(person)) {
completion.splice(completion.indexOf(person), 1);
} else return true;
});
}
console.log(solution(['kiki', 'leo', 'eden'], ['eden', 'kiki']));
console.log(solution(['marina', 'josipa', 'nikola', 'vinko', 'filipa'], ['marina', 'josipa', 'nikola', 'filipa']));
console.log(solution(['stanko', 'mislav', 'mislav', 'ana'], ['stanko', 'ana', 'mislav']));
CodePudding user response:
for (let i in completion){
sorted_index = participant.indexOf(completion[i]);
answer = participant.splice(sorted_index, 1);
}