Return the first duplicate number from an array in JavaScript


We are required to write a function that returns the index of the very first element that appears at least twice in the array. If no element appears more than once, we have to return -1. The condition is that we have to do this in constant space (i.e., without utilizing extra memory).

Let’s devise the solution for this problem. We will use a for loop to iterate over the array and use the Array.prototype.lastIndexOf() method to check for duplicates.

Example

const firstDuplicate = arr => {
   for(let i = 0; i < arr.length; i++){
      if(arr.lastIndexOf(arr[i]) !== i){
         return i;
      };
   };
   return -1;
}
console.log(firstDuplicate([3, 5, 6, 8, 5, 3])); // 0
console.log(firstDuplicate([0, 1, 2, 3, 4, 4, 5])); // 4
console.log(firstDuplicate([0, 1, 1, 2, 3, 4, 4, 5])); // 1
console.log(firstDuplicate([0, 1, 2, 3, 4, 9, 5])); // -1

Output

The output in the console will be −

0
4
1
-1

Updated on: 26-Aug-2020

477 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements