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

101
Visualizações
Develop a JavaScript to Find the position of 3rd occurrence of the given string “efg” I/P:abcefgacefgabcceftyefghjklop O/p:20

I developed a logic for the above problem but i couldnt get the desired result.

    function thirdOccurence(string){
    var count = 0;
    var i=0;
    var result = 0;
    while(i<string.length){
    if(string[i]=='e' && string[i+1]=='f' && string[i+2]=='g')
    {
        count = count+1;
        i+3;
        if(count==3)
        {
                result = i+1;
                break;
        }
    }
    else
        i++;
    }     
    }*

here the string is the input - abcefgacefgabcceftyefghjklop -output should be 20 since we need to find position. I have a working code but with a different logic. But i need to know why this is not working.

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

0

The problem was with the line where you increment the i variable by 3: i += 3. This meant you jumped 3 indexes forward, before the final condition if(count==3). But if you increment i by 3 after this final condition - everything works as expected :)

function thirdOccurence(string) {
  var count = 0;
  var i = 0;
  var result = 0;
  while (i < string.length) {
    if (string[i] === "e" && string[i + 1] === "f" && string[i + 2] === "g") {
      count += 1;
      if (count === 3) {
        result = i + 1;
        break;
      }
      i += 3;
    } else {
      i++;
    }
  }
  return result
}

console.log('result should be 20:', thirdOccurence('abcefgacefgabcceftyefghjklop'))

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