702889. Find Duplicate Element

Easy

Find Duplicate Element

Slug: find-duplicates-under-given-constraints0856

Difficulty: Easy

Id: 702889

Topic Tags: Arrays, Data Structures

Company Tags: Yahoo

Summary

Given an array of integers, we need to find the duplicate element (if any) in the given array. The array is guaranteed to have at least one duplicate.

Detailed Explanation

To solve this problem, we can use a simple algorithm that iterates through the array and checks for duplicates. We keep track of the elements we've seen so far using a set.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty set seen to store unique elements.
  2. Iterate through the given array.
  3. For each element, check if it's already present in the seen set.
  4. If the element is not in the set, add it to the set and move on to the next element.
  5. If the element is already in the set, it's a duplicate; return the element.

Here's an example:

Suppose we have the array [1, 2, 3, 4, 2]. We iterate through the array and check for duplicates as follows:

seen = {}
for i in range(len(arr)):
    if arr[i] in seen:
        return arr[i]
    else:
        seen.add(arr[i])

Time complexity: O(n), where n is the size of the input array.

Space complexity: O(n), as we need to store all unique elements in the seen set.

Optimized Solutions

Java

View on GeeksforGeeks
public int findDuplicate(int[] arr) {
    Set<Integer> seen = new HashSet<>();
    for (int num : arr) {
        if (!seen.add(num)) {
            return num;
        }
    }
    return -1; // no duplicate found
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.