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:
- Initialize an empty set
seento store unique elements. - Iterate through the given array.
- For each element, check if it's already present in the
seenset. - If the element is not in the set, add it to the set and move on to the next element.
- 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
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
}