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.
1def repeatedNTimes(nums):
2 counts = {}
3 for num in nums:
4 counts[num] = counts.get(num, 0) + 1
5 if counts[num] > 1:
6 return num
7
8print(repeatedNTimes([1, 2, 3, 3]))
9
The Python solution uses a dictionary to map each number to its occurrence count. The function returns immediately when a count greater than one is detected.
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
With JavaScript, we sort using Array.prototype.sort()
. Checking for equal, adjacent elements post-sort reveals the solution.