Sponsored
Sponsored
This approach uses a hashmap (or dictionary) to store the count of each element in the array. By iterating through the array and updating the map, we can easily identify the element that repeats n
times by checking the count value.
Time Complexity: O(N), where N is the length of the nums array because we iterate over it once.
Space Complexity: O(1), since the hashmap is of a fixed size of 10001.
1function repeatedNTimes(nums) {
2 const map = {};
3 for (const num of nums) {
4 if (map[num]) return num;
5 map[num] = true;
6 }
7}
8console.log(repeatedNTimes([1, 2, 3, 3]));
9
The JavaScript version uses an object as a hashmap for counting elements. The loop returns the first number already present in the map, indicating a repeat.
In this method, we first sort the array. If an element is repeated n
times and the rest are unique, the repeated element must be at the center of the sorted array, appearing consecutively. Checking the middle indexes should reveal the repeated element.
Time Complexity: O(N log N), due to the sorting process.
Space Complexity: O(1) in place sorting.
1
The C solution sorts the array with qsort
, then checks adjacent elements for equality. The repeated element will be found in this check.