Find Duplicate Element
Problem statement
Given an array of integers A
, find one number that repeats. Find the repeated element and return it. If there are no duplicate elements present in the input array, return -1
.
Examples
Example 01:
Input: A = [3, 4, 1, 4, 2]
Output: 4
Example 02:
Input: A = [-7, 19, 1, 4, 2]
Output: -1
Example 03:
Input: A = [1, 1, 4, 2, 1]
Output: 1 // 1 appeared 3 times in the array
Thought process
Before writing pseudo code, come up with questions and ask the interviewer.
- Is the input array sorted?
- Should we return
-1
, when the input array is empty?
Algorithm
- Create a
HashSet
and store the first element. - Iterate through all the elements.
- Check if they exist in the
HashSet
; if yes, return the element. If not, store the element in theHashSet
. - Continue the process until the last iteration. If there is no repeating element, return
-1
.
Solution
import java.util.HashSet;
public class FindDuplicateElement {
public static void main(String[] args) {
int[] A = {-7, 5, 1, 4, 2, 2};
System.out.println(findDuplicate(A));
}
private static int findDuplicate(int[] A) {
HashSet<Integer> uniqueElements = new HashSet<>();
for (int el : A) {
if (uniqueElements.contains(el)) {
return el;
}
uniqueElements.add(el);
}
return -1;
}
}
Complexity analysis
- Time complexity:
O(n)
, we need to traverse all the elements in the array. If there aren
items, then the time complexity to run the algorithm takesO(n)
. - Space complexity:
O(n)
, this is because we are storingn
elements in theHashSet
.