How to find first duplicate in array in Javascript

javascript algorithms

I was asked to write the solution for this question with the following restrictions:

  • O(1) space complexity
  • O(n) time complexity

The function should return -1 in the case of no duplications.

Here is the solution:

function firstDuplicate(array) {
  const arraySet = new Set();
  for(const value of array) {
    if(arraySet.has(value)) return value;
  return -1;

Here is an example of results:

console.log(firstDuplicate([1,2,3,4,3,2,5])) // 3
console.log(firstDuplicate([1,2,3,4,6,7,8])) // -1
console.log(firstDuplicate([-2,2,3,5,0,-2])) // -2
comments powered by Disqus