Write a program in C++ to find the most frequent element in a given array of integers

C++Server Side ProgrammingProgramming

Let’s suppose we have an array of integers of size N. The task is to find the most frequent element present in the given array of integers. For example,


N = 8
A[ ] = {1,2,4,3,3,1,1,5}



Explanation − In the given array of integers, the most appearing number is ‘1’. Thus the output is ‘1’.


N = 6
A[ ] = {1,4,4,4,1,1}





Explanation: In the given array of integers, the most appearing number is ‘1’ and ‘4’. Thus we can return the output to any one of them.

Approach to solve this problem

The given array contains multiple integers in which we have to find the most frequent element present in the array. To solve this problem in linear time O(n) and Linear Space O(n), we can use the approach of a hashmap.

In this approach, we will create an unordered map(STL Library) consist of key-value pair in which the key will be an element and the Value will be the occurrence of the element. While traversing through the map we will find the maximum occurrence of the number and return the number as Output.

  • Take Input an array of size N.

  • An Integer function maxOccurrence(int A[], int size) takes an array and its size as an input and returns the numbers with maximum frequency.

  • Creating a hashmap of all the elements of the array by taking the key as an element and value as its frequency.

  • Iterating over the map and checking if any of the elements having the most frequency then return the result as the number. Otherwise, if there is not any number present in the array then return ‘-1’.


 Live Demo

using namespace std;
int maxOccurrence(int A[], int size){
   int mxcount=0;
   int res=-1;
   for(int i=0;i<size;i++){
   for(auto x:mp){
         res= x.first;
   return res;
int main(){
   int N=6;
   int A[N]= {1,4,4,4,2,1};
   int ans= maxOccurrence(A,N);
   return 0;


If we will run the above code, it will print the output as,


4 has the frequency of 3, which is the maximum frequency from all the other numbers in the given array.

Updated on 05-Feb-2021 12:21:32