So I am doing a course on algorithms to get ready for interviews and something happened and now I am really confused about what is going on behind the scenes with this problem. The problem is pretty easy just need to check for the same items in two arrays. However, you cant use nested loops because it needs to have a runTime faster than 1000ms. Here is my code below and it worked first try!
const intersection = (a, b) => {
count = {}
answer = [];
for(let i = 0; i < a.length; i++){
const num = a[i]
count[num] += 1;
}
for(arrb of b){
if(arrb in count){
answer.push(arrb)
}
}
return answer
};
So I passed the test and was happy I got it easily then I realized I had a typo setting the count. I meant to do count[num] = 1 NOT += However after testing it again with the = my code kept failing the test because of 2000ms+ response times on the final test(which is)
const a = [];
const b = [];
for (let i = 0; i < 50000; i += 1) {
a.push(i);
b.push(i);
}
intersection(a, b) // -> [0,1,2,3,..., 49999]
So I am really confused why it runs perfectly when there is a += but not a normal = since doing += just returns an object with the values set to NAN.