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

230
Vistas
Three Sum Algorithm can't find bug

I'm trying to solve Three Sum (find all triplets that add to 0 within an array avoiding duplicate cases) but currently running into a bug I can't seem to find.

When the input is [-1,0,1,2,-1,-4], it works fine.

With this input however, [-1,0,1,2,-1,-4,-2,-3,3,0,4] I'm getting this array as output:

[[-1,-1,2],[-1,0,1],[-2,0,2],[-3,0,3],[-3,1,2],[-4,0,4],[-4,1,3]].

The correct output should be

[[-4,0,4],[-4,1,3],[-3,-1,4],[-3,0,3],[-3,1,2],[-2,-1,3],[-2,0,2],[-1,-1,2],[-1,0,1]]

So for some reasons my solution is omitting the triplets [-3,-1,4] and [-2,-1,3].

var threeSum = function (nums) {
    const sorted = nums.sort()
    const output = []
    for (let i = 0; i < sorted.length - 2; i++)
        if (i === 0 || (i > 0 && sorted[i] !== sorted[i - 1])) {
            let lower = i + 1
            let higher = sorted.length - 1

            while (lower < higher) {
                const currentSum = sorted[i] + sorted[lower] + sorted[higher];
                if (currentSum === 0) {
                    output.push([sorted[i], sorted[lower], sorted[higher]])
                    while (sorted[lower] === sorted[lower + 1]) lower++
                    while (sorted[higher] === sorted[higher - 1]) higher--
                    lower++
                    higher--
                }

                else if (currentSum < 0) {
                    lower++
                } else {
                    higher--
                }
            }
        }
    }
    return output
 };
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

By default Javascript sorts via string comparison.

You want to sort numerically so use

nums.sort(function(a, b){return a - b});
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