Find first duplicate item in array in linear time JavaScript

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 ?

4

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

Using Set Data Structure

The most efficient approach uses a Set to track elements we've already seen. As we iterate through the array, we check if each element exists in the Set. If it does, we found our first duplicate.

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));
4

How It Works

The algorithm processes elements in order:

  1. Element 3: Not in Set, add it ? Set: {3}
  2. Element 4: Not in Set, add it ? Set: {3, 4}
  3. Element 1: Not in Set, add it ? Set: {3, 4, 1}
  4. Element 4: Found in Set! Return 4

Edge Cases

// No duplicates
console.log(findRepeatedNumber([1, 2, 3])); 

// Single element
console.log(findRepeatedNumber([5])); 

// Empty array
console.log(findRepeatedNumber([])); 
-1
-1
-1

Time and Space Complexity

Complexity Value Explanation
Time O(n) Single pass through array
Space O(n) Set stores up to n unique elements

Conclusion

Using a Set provides an efficient O(n) time solution to find the first duplicate in an array. The algorithm stops at the first duplicate encountered, making it optimal for this problem.

Updated on: 2026-03-15T23:19:00+05:30

352 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements