2

I want to find the element in array which has maximum occurrences and know the number of occurrences. Please suggest me fastest C++ code to do so.(You are free to use STL if that can be of any help.)

tchrist
  • 78,834
  • 30
  • 123
  • 180
Kartik Khare
  • 71
  • 1
  • 9

2 Answers2

5

Here is one way of doing it in C++11:

#include <vector>
#include <map>

int most_frequent_element(std::vector<int> const& v)
{   // Precondition: v is not empty
    std::map<int, int> frequencyMap;
    int maxFrequency = 0;
    int mostFrequentElement = 0;
    for (int x : v)
    {
        int f = ++frequencyMap[x];
        if (f > maxFrequency)
        {
            maxFrequency = f;
            mostFrequentElement = x;
        }
    }

    return mostFrequentElement;
}

You could use the above function this way:

#include <iostream>

int main()
{
    std::vector<int> v { 1, 3, 5, 6, 6, 2, 3, 4, 3, 5 };
    std::cout << most_frequent_element(v);
}

Here is a live example.

With a minor modification, the above function can be generalized to work with any container (not just std::vector):

template<typename T>
typename T::value_type most_frequent_element(T const& v)
{    // Precondition: v is not empty
    std::map<typename T::value_type, int> frequencyMap;
    int maxFrequency = 0;
    typename T::value_type mostFrequentElement{};
    for (auto&& x : v)
    {
        int f = ++frequencyMap[x];
        if (f > maxFrequency)
        {
            maxFrequency = f;
            mostFrequentElement = x;
        }
    }

    return mostFrequentElement;
}

Thanks to template type deduction, you would call the above function template exactly like you called the original one.

Here is a live example.

Also, for even better performance, you may consider using C++11's std::unordered_map rather than std::map. std::unordered_map gives you amortized O(1) complexity for insertion and lookup. I'll leave its usage in the above examples up to you as an exercise.

Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
1

You can have O(n log n) solution to this problem in C++.

First use an O(n log n) sort (Heap Sort, Merge Sort, Quick Sort, etc.) to sort the number of elements in the list. If you don't care about the complexity of the algorithm sort the list using Bubble Sort. In that case the complexity of the algorithm will become O(n2).

Then use the following code which takes O(n) time to find the element with highest occurrence from the sorted list.

maxfreq=0;
freq=1;
for(i=0;i<(MAX-1);i++)
{
  if(list[i]==list[i+1])
  {
    freq++;
    if(freq > maxfreq)
    {
      maxfreq=freq;
      maxind=i;
    }
  }
  else
  {
    freq=1;
  }
}
cout<<"Element "<<list[maxind]<<" occurs "<<maxfreq<<" times in the list";

The total time taken is O(log n + n). Thus the complexity of the algorithm is O(log n).

Deepu
  • 7,592
  • 4
  • 25
  • 47