Given an array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times. Return the element that is repeated N times.
A always has exactly one element repeated N times?To solve this problem efficiently, I will use the following approach:
This approach ensures that we only make a single pass through the array and keep an auxiliary space proportional to the number of unique elements, which makes the algorithm efficient in terms of both time and space.
#include <vector>
#include <unordered_set>
class Solution {
public:
int repeatedNTimes(std::vector<int>& A) {
std::unordered_set<int> seen;
for(int num : A) {
if(seen.count(num)) {
return num;
}
seen.insert(num);
}
// If input constraints are guaranteed, the function will always return from within the loop.
return -1;
}
};
seen to keep track of elements we have encountered.num in array A.num, check if it exists in the set seen.
num.num into the set.By iterating through the array and checking for the repeated element as described, the solution ensures 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?