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

200
Vistas
Javascript reduce method returns wrong value

I need to find the length of the longest substring in a string, I do it by this:

var lengthOfLongestSubstring = function(s) {
    let arr = [];
    let obj = {};
    for(let i = 0; i<s.length; i++){
        
        if(arr.indexOf(s[i])!==-1){
            copy=arr.slice();
            obj[i]=copy;
            arr=[];
            arr.push(s[i])
        }
        else{
            arr.push(s[i]);
        }
    }
    console.log(obj)
    return Object.values(obj).reduce((acc, nextItem)=>{
        if(acc&acc.length>=nextItem&&nextItem.length){
            return acc.length;
        }
        else{
            return nextItem.length
        }
    }, [])
};

console.log (lengthOfLongestSubstring ('abcabcbb'));

For test case "abcabcbb" it returns 1 instead of 3 and I don't understand why; btw what complexity (in terms of big O) would my code achieve?

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

0

the variant you have should work, just fix few typos in your code:

  return Object.values(obj).reduce((acc, nextItem) => acc >= nextItem.length ? acc.length : nextItem.length , 0)
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