Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

187
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda