0

Challenge was to find duplicates in an array.

function firstDuplicate(a) {
  const duplicates = a.map((el,idx) => {
    let myVar = a.indexOf(el,idx+1);
    if (myVar >= 0) return myVar;
   }).filter(el => el);
  if (duplicates.length){
    return Math.min(... duplicates) + 1;
  } else {
    return -1;
  }
}
console.log(firstDuplicate([3,3,3])); // 2

It seems 2 is the correct answer. From the challenge description: "find the first duplicate number for which the second occurrence has the minimal index. In other words, if there are more than 1 duplicated numbers, return the number for which the second occurrence has a smaller index than the second occurrence of the other number does."

Then I tried the solution using Set.

// Second attempt

function firstDuplicate(a) {
  let duplicates = new Set();
  
  for (let el of a){
    let sizeOfDuplicates = duplicates.size;
    duplicates.add(el);
    
    if (sizeOfDuplicates + 1 !== duplicates.size) {
      return el;
    }
  }
  
  return -1;
}

console.log(firstDuplicate([3,3,3])); // 3

Question The second version passes all the tests, but I think the first version is more correct. Shouldn't the answer be 2 instead of 3?

Edit

For clarity, I'm adding some more text:

"Example

For a = [2, 3, 3, 1, 5, 2], the output should be firstDuplicate(a) = 3.

There are 2 duplicates: numbers 2 and 3. The second occurrence of 3 has a smaller index than than second occurrence of 2 does, so the answer is 3."

Tyler L
  • 835
  • 2
  • 16
  • 28
  • 1
    Like this one? https://stackoverflow.com/questions/39346182/javascript-how-to-find-first-duplicate-value-and-return-its-index – Jorg Mar 18 '18 at 23:56
  • 1
    Judging from the text, `3` is the correct answer in your examples. The number is the result, not the index. – ASDFGerte Mar 19 '18 at 00:01

0 Answers0