You are given an array A
that contains 2N elements. In this array, there is exactly one element that is repeated N times. Your task is to find that repeated element.
Example:
Input: [1, 2, 3, 3]
Output: 3
Input: [2, 1, 2, 5, 3, 2]
Output: 2
Input: [5, 1, 5, 2, 5, 3, 5, 4]
Output: 5
Given that one element repeats N times in an array of size 2N, the repeated element will be the only element meeting this criterion.
We can use the following strategies to solve this problem:
HashSet
to keep track of elements we have seen.We’ll go with the HashSet approach for optimal time complexity and simplicity.
import java.util.HashSet;
public class Solution {
public int repeatedNTimes(int[] A) {
HashSet<Integer> set = new HashSet<>();
for (int num : A) {
if (!set.add(num)) { // If add returns false, then num is already in set.
return num;
}
}
// According to the problem statement, there will always be a solution,
// So this line should never be reached.
return -1;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] arr1 = {1, 2, 3, 3};
int[] arr2 = {2, 1, 2, 5, 3, 2};
int[] arr3 = {5, 1, 5, 2, 5, 3, 5, 4};
System.out.println(solution.repeatedNTimes(arr1)); // Output: 3
System.out.println(solution.repeatedNTimes(arr2)); // Output: 2
System.out.println(solution.repeatedNTimes(arr3)); // Output: 5
}
}
This approach ensures that we find the N-repeated element efficiently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?