Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

190
Visualizações
Setting an object's value with += instead of = is making my runtime 10x faster, and not sure why

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.

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda