Finding most occurred element in an array in C++

In this tutorial, we will learn how to find the most occurred element in an array in C++ using hashing which will take linear time to solve this problem. We will create an array of the maximum range of number in an array. Suppose that number is 10000, then we will create an array of size 10000, this particular solution will be good if all the elements lie under the range of 10^7.

Consider the following example:

Let the array be: 1, 1, 2, 3, 4, 4, 5

suppose we created an array to size 10. We will initialize the whole new array to 0.

Then we will traverse the given array and increment our new array if that particular array element encounters.

Like here 1 has occurred 2 times then index 1 of the new array will be incremented to 2 and so other elements index will be incremented.

Now we will traverse our new array and find the element with the highest frequency. Let implement the above-mentioned theory in our code.




Program to find the most occurred element in an array in C++

Cpp source code:

// Program to find most occured element in an array
#include<bits/stdc++.h>
using namespace std;
int main()
{
  int n;
  cout<<"Enter size of array: ";
  cin>>n;
  int arr[n];
  cout<<"\nEnter array elements:\n";
  for(int i=0;i<n;i++)
  {
    cin>>arr[i];
  }
  
  // Declaring new array and initialize it to 0
  int new_arr[10001]={0};
  for(int i=0;i<n;i++)
  {
    new_arr[arr[i]]++;
  }
  int max=0;
  int index;
  for(int i=0;i<=10000;i++)
  {
    if(max<new_arr[i])
    {
      index=i;
      max=new_arr[i];
    }
  }
  cout<<"\nMost occurred element in the array is "<<index<<"\n";
  return 0;
}

Follow the comment in the above program to understand what we did.

Input/Output:

Enter size of array: 10

Enter array elements:
2 2 3 4 5 19 19 19 18 10

Most occurred element in the array is 19

You may also learn:

Checking for Duplicacy in an array using Hashing Technique in Java

Pair with a given sum in an array using HashSet in Java

Do not forget to comment if you find anything wrong in the post or you want to share some information regarding the same.


Leave a Reply

Your email address will not be published. Required fields are marked *