-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdup_arr_hashmap.cpp
54 lines (45 loc) · 1.2 KB
/
dup_arr_hashmap.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <bits/stdc++.h>
using namespace std;
vector<int> findDuplicates(vector<int> &arr) {
// Step 1: Create an empty unordered map to store
// element frequencies
int n = arr.size();
unordered_map<int, int> freqMap;
vector<int> result;
// Step 2: Iterate through the array and count
// element frequencies
for (int i = 0; i < n; i++) {
freqMap[arr[i]]++;
}
// Step 3: Iterate through the hashmap to find duplicates
for (auto &entry : freqMap) {
if (entry.second > 1) {
result.push_back(entry.first);
}
}
// Step 4: If no duplicates found, add -1 to the result
if (result.empty()) {
result.push_back(-1);
}
// Step 6: Return the result vector containing
// duplicate elements or -1
return result;
}
int main() {
vector<int> arr;
int n;
cout << "Enter the number of elements in the array: ";
cin>>n;
cout << "Enter the elements of the array: ";
for(int i=0;i<n;i++)
{
int x;
cin>>x;
arr.push_back(x);
}
vector<int> duplicates = findDuplicates(arr);
for (int element : duplicates) {
cout << element << " ";
}
return 0;
}