# Most frequent element in an array in C++

We are given a array and we need to find the most frequent element from it. Let's see an example.

Input

arr = [1, 2, 3, 3, 2, 2, 1, 1, 2, 3, 4]

Output

2

In the above array, 2 occurs 4 times which is most frequent than any other in the array.

## Algorithm - 1

• Initialise the array.

• Initialise a map to store the frequency of each element.

• Count the frequency of each element and store it in the map.

• Iterate over the map and find the element with most frequency.

• Return the element.

## Algorithm - 2

• Initialise the array.
• Sort the given array.
• Maintain the variables for max count, result and current element count.
• Find the max count element by iterating over the array.
• Same elements resides side by side.
• Return the result.

## Implementation

Following is the implementation of the above algorithm in C++

#include <bits/stdc++.h>
using namespace std;
int getMostFrequentNumber(int arr[], int n) {
unordered_map<int, int> elements;
for (int i = 0; i < n; i++) {
elements[arr[i]]++;
}
int maxCount = 0, res = -1;
for (auto i : elements) {
if (maxCount < i.second) {
res = i.first;
maxCount = i.second;
}
}
return res;
}
int main() {
int arr[] = { 1, 2, 3, 3, 2, 2, 1, 1, 2, 3, 4 };
int n = 11;
cout << getMostFrequentNumber(arr, n) << endl;
return 0;
}

## Output

If you run the above code, then you will get the following result.

2