Description
You are given an integer array nums with the following properties:
nums.length == 2 * n.numscontainsn + 1unique values,nof which occur exactly once in the array.- Exactly one element of
numsis repeatedntimes.
Return the element that is repeated n times.
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] <= 104numscontainsn + 1unique elements and one of them is repeated exactlyntimes.
Solutions
This function finds the element repeated n times in an array of size 2n, using a Map to count occurrences. For each number it first looks up how many times it has already been seen (map.get(num) || 0, where the || 0 defaults to zero for new numbers). If that prior count is n - 1, the current occurrence is the nth one, so the function returns the number immediately — checking before updating the map saves an extra lookup compared to incrementing first. Otherwise it stores the incremented count and moves on. The trailing return -1 is only a safety net, since a valid input always contains an element repeated n times.
/**
* @param {number[]} nums
* @return {number}
*/
var repeatedNTimes = function(nums) {
const n = nums.length / 2;
const map = new Map();
for (const num of nums) {
const count = map.get(num) || 0;
if (count === n - 1) {
return num;
}
map.set(num, count + 1);
}
return -1;
};