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

205
Vistas
Why does this code work and why do we have to increment index twice?

I am learning how to code Javascript. Been learning for 6 months now. I'm working through code wars problems to help me with my logic when it comes to algorithms.

I was working on this CodeWars problem Find All Pairs

Here was my logic and code:

  SET a pair count variable 
  SET a sorretd array varible 
  FOR LOOP iterate though the array
  SET index = 0
  WHILE index < array argument 
  Increment index
  IF the current iteration is equal to the index + 1 
  ADD to the pair count varible 
RETURN count variable

CODE:

function duplicates(array) {
  let pairResult = 0;
  let sorrtedArray = array.sort();

  for (let index = 0; index < sorrtedArray.length; index++) {
    if (sorrtedArray[index + 1] ===  sorrtedArray[index]) {
      pairResult += 1;
      index++
      console.log(index);
    }
  }
  return pairResult;
}

The test output I was getting with the two test cases were:

console.log(duplicates([1, 2, 5, 6, 5, 2])) ====> 2

console.log(duplicates([1, 2, 2, 20, 6, 20, 2, 6, 2])); ====> 5

I know it was counting 2s three times, at least that is what it seems. Anyways, I had to look at the solution. Below is a code that was almost identical to mine that worked.

function duplicates(array){
  //Make the magic happen
    const newArray = array.sort((a,b) => a-b);
    if (newArray.length <= 1) return 0;
    
    let count = 0;
    
    for (let i = 0; i < newArray.length ; i++) {
      if (newArray[i] == newArray[i+1]) {
        count++;
        i++;
      }
    }
    return count;
  }

My question is why are we incrementing the i++ again within the for loop when were incrementing it already when we declare the for loop?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

It's there to avoid over-counting duplicates. As the requirements say:

If there are more pairs of a certain number, count each pair only once. E.g.: for [0, 0, 0, 0] the return value is 2 (= 2 pairs of 0s)

For example, given

[2, 2, 2]

you'd want to count one set of pairs.

When a pair is found

for (let i = 0; i < newArray.length ; i++) {
  if (newArray[i] == newArray[i+1]) {
    count++;
    i++;
  }
}

you've now checked off both indicies i and i + 1 - if you proceeded to compare indicies i + 1 and i + 2 on the next iteration, you'd be counting the item at i + 1 one too many.

By doing i++ inside the loop, you ensure that you skip over to the next unchecked item, without iterating over something you've already checked, to avoid double-counting.

about 4 years ago · Juan Pablo Isaza Denunciar

0

There was an increment to change the value index value what has already been matched. (newArray[i] == newArray[i+1]) that means i+1 is equal which is not required to be tested.

Suggest me any changes here.

about 4 years ago · Juan Pablo Isaza Denunciar
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