Skip to content
Advertisement

Find first duplicate in an array

Given an array a that contains only numbers in the range from 1 to a.length, 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. If there are no such elements, return -1.

My code:

JavaScript

The code above will be OK when the input is [2, 4, 3, 5, 1] but if the input is [2, 1, 3, 5, 3, 2] the output is wrong. The second duplicate occurrence has a smaller index. The expected output should be 3.

How can I fix my code to output the correct result?

Advertisement

Answer

JavaScript

By traversing the array backwards, you will overwrite any previous duplicates with the new, lower-indexed one.

Note: this returns the value (not index), unless no duplicate is found. In that case, it returns -1.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement