Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

91
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!