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

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

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 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!