N-Repeated Element in Size 2N Array
EasyUpdated: Aug 2, 2025
Practice on:
Problem
You are given an integer array nums with the following properties:
nums.length == 2 * n.numscontainsn + 1unique elements.- Exactly one element of
numsis repeatedntimes.
Return the element that is repeatedn times.
Examples
Example 1
Input: nums = [1,2,3,3]
Output: 3
Example 2
Input: nums = [2,1,2,5,3,2]
Output: 2
Example 3
Input: nums = [5,1,5,2,5,3,5,4]
Output: 5
Constraints
2 <= n <= 5000nums.length == 2 * n0 <= nums[i] <= 10^4numscontainsn + 1unique elements and one of them is repeated exactlyntimes.
Solution
Method 1 -
Intuition
Since only one element is repeated n times, and all others appear once, we can use a set to find the repeated element efficiently.
Approach
Iterate through the array, add each element to a set. The first element that is already in the set is the repeated one.
Code
C++
int repeatedNTimes(vector<int>& nums) {
unordered_set<int> seen;
for (int x : nums) {
if (seen.count(x)) return x;
seen.insert(x);
}
return -1;
}
Go
func repeatedNTimes(nums []int) int {
seen := make(map[int]bool)
for _, x := range nums {
if seen[x] { return x }
seen[x] = true
}
return -1
}
Java
public int repeatedNTimes(int[] nums) {
Set<Integer> seen = new HashSet<>();
for (int x : nums) {
if (seen.contains(x)) return x;
seen.add(x);
}
return -1;
}
Kotlin
fun repeatedNTimes(nums: IntArray): Int {
val seen = mutableSetOf<Int>()
for (x in nums) {
if (x in seen) return x
seen.add(x)
}
return -1
}
Python
def repeatedNTimes(nums):
seen = set()
for x in nums:
if x in seen:
return x
seen.add(x)
return -1
Rust
use std::collections::HashSet;
fn repeated_n_times(nums: Vec<i32>) -> i32 {
let mut seen = HashSet::new();
for x in nums {
if !seen.insert(x) { return x; }
}
-1
}
TypeScript
function repeatedNTimes(nums: number[]): number {
const seen = new Set<number>();
for (const x of nums) {
if (seen.has(x)) return x;
seen.add(x);
}
return -1;
}
Complexity
- ⏰ Time complexity:
O(n)where n is the length of nums. - 🧺 Space complexity:
O(n)for the set.