Most frequent element in an array in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the most frequent element in an array.

Let's see the steps to solve the problem.

  • 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.

Example

Let's see the code.

 Live Demo

#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

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 01-Jul-2021 06:24:27
Advertisements