class Solution:
def repeatedNTimes(self, nums):
seen = set()
for num in nums:
if num in seen:
return num
seen.add(num)
class Solution {
public:
int repeatedNTimes(vector<int>& nums) {
unordered_set<int> seen;
for (int num : nums) {
if (seen.count(num)) return num;
seen.insert(num);
}
return -1; // Should never reach here
}
};
class Solution {
public int repeatedNTimes(int[] nums) {
HashSet<Integer> seen = new HashSet<>();
for (int num : nums) {
if (seen.contains(num)) return num;
seen.add(num);
}
return -1; // Should not reach here
}
}
var repeatedNTimes = function(nums) {
const seen = new Set();
for (const num of nums) {
if (seen.has(num)) return num;
seen.add(num);
}
};
You are given an array nums
of size 2N
where there are exactly N+1
unique elements, and exactly one of these elements is repeated N
times. All other elements appear only once. Your task is to find and return the element that is repeated N
times.
For example, if nums = [1,2,3,3]
, then N = 2
and the answer is 3
because it appears twice.
To solve this problem, let's first understand what makes the repeated element special. The array has 2N
elements, and among them, only one element appears N
times, while the rest appear just once. This means the repeated element stands out by its frequency.
A brute-force approach would be to count the occurrences of every number in the array and return the one with count N
. While this works, it's not the most efficient way, especially for larger arrays.
To optimize, we can leverage the guarantee that only one element is repeated, and it must appear at least twice. As we scan the array, the first element we see twice is guaranteed to be the answer. This is much faster because we can stop as soon as we find the repeated element, rather than counting all elements.
nums
array.
This approach is both time and space efficient, and it directly leverages the problem's constraints.
Let's walk through the solution with the input nums = [5,1,5,2,5,3,5,4]
.
seen = {}
5
. Not in seen
. Add it: seen = {5}
1
. Not in seen
. Add it: seen = {1,5}
5
. Already in seen
! This is the repeated element. Return 5
.As you can see, the solution finds the answer quickly, without needing to check all elements or count frequencies for every number.
The optimized approach is as efficient as possible for this problem, both in time and space.
In summary, we solved the N-Repeated Element in Size 2N Array problem by using a set to track seen elements as we scan the array. As soon as we encounter an element we've seen before, we return it as the answer. This leverages the problem's guarantee of exactly one repeated element, making the solution both simple and efficient. The key insight is to stop early and use fast set lookups, rather than counting every element's frequency.