
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Most Frequent Element in Array Using C++
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,
Input-1 −
N = 8 A[ ] = {1,2,4,3,3,1,1,5}
Output −
1
Explanation − In the given array of integers, the most appearing number is ‘1’. Thus the output is ‘1’.
Input-2 −
N = 6 A[ ] = {1,4,4,4,1,1}
Output-a −
1
Output-b −
4
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’.
Example
#include<bits/stdc++.h> using namespace std; int maxOccurrence(int A[], int size){ int mxcount=0; int res=-1; unordered_map<int,int>mp; for(int i=0;i<size;i++){ mp[A[i]]++; } for(auto x:mp){ if(x.second>mxcount){ res= x.first; mxcount=x.second; } } return res; } int main(){ int N=6; int A[N]= {1,4,4,4,2,1}; int ans= maxOccurrence(A,N); cout<<ans<<endl; return 0; }
Output
If we will run the above code, it will print the output as,
4
4 has the frequency of 3, which is the maximum frequency from all the other numbers in the given array.