- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Articles
- Find the second most frequent element in array JavaScript
- C# program to find the most frequent element
- Finding the most frequent word(s) in an array using JavaScript
- Find most frequent element in a list in Python
- Write a program in C++ to find the most frequent element in a given array of integers
- Most Frequent Subtree Sum in C++
- Find Second most frequent character in array - JavaScript
- Most Frequent Number in Intervals in C++
- Program to find out the index of the most frequent element in a concealed array in Python
- Program to find frequency of the most frequent element in Python
- Write a program in C++ to find the top K frequent element in an array of integers
- Program to find second most frequent character in C++
- Second most frequent character in a string - JavaScript
- Finding the second most frequent character in JavaScript
- Python program for most frequent word in Strings List

Advertisements