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

265
Visualizações
Recurring problem without using hash tables

This is a code for first recurring element and lets say as an input [2,5,5,2,3,5,1,2,4] return 5 because the pairs are before 2,2 and im not able to return 5

function firstRecurring(input) {
  for (let i = 0; i < input.length; i++) {
    for (let j = i + 1; j < input.length; j++) {
      if(input[i] === input[j]) {
        return input[i];
      }
    }
  }
  return undefined
}

console.log(firstRecurring([2,5,5,2,3,5,1,2,4]));

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your j index runs immediately to the end of the array. You should instead put a limit to how far you look and check the section before. So j should not be looking ahead, but back:

function firstRecurring(input) {
  for (let i = 1; i < input.length; i++) {
    for (let j = 0; j < i; j++) {
      if(input[i] === input[j]) {
        return input[i];
      }
    }
  }
  return undefined;
}

console.log(firstRecurring([2,5,5,2,3,5,1,2,4]));

Of course, this can be made more efficient by using a set of encountered values. You can then also use the for..of syntax. And... return undefined is really not necessary, as it is the default behaviour:

function firstRecurring(input) {
  let set = new Set;
  for (let val of input) {
    if (set.has(val)) return val;
    set.add(val);
  }
}

console.log(firstRecurring([2,5,5,2,3,5,1,2,4]));

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