Second Frequently Occurring Number in C++

J16
1 min readMay 19, 2021

Hey there!

Question: Print the second frequently occurring number.

So, there are several method to achieve this, in this article we’ll see two method.

Solution 1:

#include<iostream>
#include<string>
using namespace std;
int repeat(int arr[],int n){
int max1=0, max2=0, count[256]={0};

for(int i=0; i<n; i++){
count[ arr[i] ]++;
}
// or change function type to char and (count [ '0' + a[i] ]++)

for(int i=0; i<256; i++){
if(count[i] > count[max1]){
max2 = max1;
max1 = i;
}
else if( count[i] > count[max2] && count[i] != count[max1] ){
max2 = i;
}
}
return max2;
}
int main() {
int arr[] = {3,2,2,3,4,4,4,8,8,8,8,9,8};
int n = sizeof(arr)/sizeof(arr[0]);
cout << repeat(arr,n);
}

Solution 2:

#include<iostream>
#include<bits/stdc++.h>
using namespace std;int secondFrequent(int num){ int count; map<int, int> indi_num; while(num > 0){
indi_num[(num%10)]++;
num /= 10;
}
map<int, int>::iterator m; int max1=0, max2=0, first_num, second_num; for(m = indi_num.begin(); m != indi_num.end(); m++){ if(m->second > max1){
max2 = max1;
max1 = m->second;
second_num = first_num;
first_num = m -> first;
}
else if( m->second > max2){
max2 = m->second;
second_num = m->first;
}
//cout << m->first << " " << m-> second << endl;
}
return second_num;
}
int main(){
int num = 1123124;
cout << secondFrequent(num);
}

Please let me know if you have any other approach to this problem.

Thanks!

--

--