Skip to content

Commit bb7b303

Browse files
authored
Merge pull request #37 from sakshi1432/patch-4
finds top three repeated elements
2 parents 02294ac + 487c049 commit bb7b303

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

top-three-repeated.cpp

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
2+
// C++ Program to Find the top three repeated numbers
3+
#include <bits/stdc++.h>
4+
using namespace std;
5+
6+
/* Function to print top three repeated numbers */
7+
void top3Repeated(int arr[], int n)
8+
{
9+
// There should be atleast two elements
10+
if (n < 3) {
11+
cout << "Invalid Input";
12+
return;
13+
}
14+
15+
// Count Frequency of each element
16+
unordered_map<int, int> fre;
17+
for (int i = 0; i < n; i++)
18+
fre[arr[i]]++;
19+
20+
// Initialize first value of each variable
21+
// of Pair type is INT_MIN
22+
pair<int, int> x, y, z;
23+
x.first = y.first = z.first = INT_MIN;
24+
25+
for (auto curr : fre) {
26+
27+
// If frequency of current element
28+
// is not zero and greater than
29+
// frequency of first largest element
30+
if (curr.second > x.first) {
31+
32+
// Update second and third largest
33+
z = y;
34+
y = x;
35+
36+
// Modify values of x Number
37+
x.first = curr.second;
38+
x.second = curr.first;
39+
}
40+
41+
// If frequency of current element is
42+
// not zero and frequency of current
43+
// element is less than frequency of
44+
// first largest element, but greater
45+
// than y element
46+
else if (curr.second > y.first) {
47+
48+
// Modify values of third largest
49+
z = y;
50+
51+
// Modify values of second largest
52+
y.first = curr.second;
53+
y.second = curr.first;
54+
}
55+
56+
// If frequency of current element
57+
// is not zero and frequency of
58+
// current element is less than
59+
// frequency of first element and
60+
// second largest, but greater than
61+
// third largest.
62+
else if (curr.second > z.first) {
63+
64+
// Modify values of z Number
65+
z.first = curr.second;
66+
z.second = curr.first;
67+
}
68+
}
69+
70+
cout << "Three largest elements are "
71+
<< x.second << " " << y.second
72+
<< " " << z.second;
73+
}
74+
75+
// Driver's Code
76+
int main()
77+
{
78+
int arr[] = { 3, 4, 2, 3, 16, 3, 15,
79+
16, 15, 15, 16, 2, 3 };
80+
int n = sizeof(arr) / sizeof(arr[0]);
81+
top3Repeated(arr, n);
82+
return 0;
83+
}

0 commit comments

Comments
 (0)