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.
1#include <iostream>
2#include <unordered_map>
3#include <vector>
4using namespace std;
5
6int repeatedNTimes(vector<int>& nums) {
7 unordered_map<int, int> count;
8 for (int num : nums) {
9 if (++count[num] > 1) return num;
10 }
11 return -1; // should never reach here
12}
13
14int main() {
15 vector<int> nums = {1, 2, 3, 3};
16 cout << repeatedNTimes(nums) << endl;
17}
18
The C++ version uses an unordered_map
to store the counts of each element in the vector. The loop returns the first number whose count exceeds one.
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.