N-Repeated Element in Size 2N Array

easy array hash set

Problem

You are given an integer array nums with a length of 2n where exactly one element is repeated n times and the remaining n elements are all distinct. Return the element that is repeated n times.

Inputnums = [1, 2, 3, 3]
Output3
The array has length 4 (n = 2). The value 3 appears n = 2 times; every other value appears once.

def repeated_n_times(nums):
    seen = set()
    for x in nums:
        if x in seen:
            return x
        seen.add(x)
    return -1
function repeatedNTimes(nums) {
  const seen = new Set();
  for (const x of nums) {
    if (seen.has(x)) return x;
    seen.add(x);
  }
  return -1;
}
class Solution {
    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;
    }
}
int repeatedNTimes(vector<int>& nums) {
    unordered_set<int> seen;
    for (int x : nums) {
        if (seen.count(x)) return x;
        seen.insert(x);
    }
    return -1;
}
Time: O(n) Space: O(n)