Find first duplicate item in array in linear time JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a read only array of n + 1 integers between 1 and n.

The function should find one number that repeats in linear time and using at most O(n) space.

For example If the input array is −

const arr = [3 4 1 4 1];

Then the output should be −

const output = 1;

If there are multiple possible answers ( like above ), we should output any one. If there is no duplicate, we should output -1.

Example

const arr = [3, 4, 1, 4, 1];
const findRepeatedNumber = (arr = []) => {
   const set = new Set();
   for (const item of arr) {
      if (set.has(item)){
         return item;
      };
      set.add(item);
   };
   return -1;
};
console.log(findRepeatedNumber(arr));

Output

This will produce the following output −

4
raja
Published on 25-Nov-2020 04:50:53
Advertisements