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

199
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
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