Array elements that appear more than once?


Here we will see one problem. We have one array. our task is to find those elements whose frequencies are more than 1. Suppose the elements are {1, 5, 2, 5, 3, 1, 5, 2, 7}. Here 1 has occurred 2 times, 5 has occurred 3 times and 2 has occurred three times, others have occurred only once. So the output will be {1, 5, 2}

Algorithm

moreFreq(arr, n)

Begin
   define map with int type key and int type value
   for each element e in arr, do
      increase map.key(arr).value
   done
   for each key check whether the value is more than 1, then print the key
End

Example

#include <iostream>
#include <map>
using namespace std;
void moreFreq(int arr[], int n){
   map<int, int> freq_map;
   for(int i = 0; i<n; i++){
      freq_map[arr[i]]++; //increase the frequency
   }
   for (auto it = freq_map.begin(); it != freq_map.end(); it++) {
      if (it->second > 1)
         cout << it->first << " ";
   }
}
int main() {
   int arr[] = {1, 5, 2, 5, 3, 1, 5, 2, 7};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout << "Frequency more than one: ";
   moreFreq(arr, n);
}

Output

Frequency more than one: 1 2 5

Updated on: 01-Aug-2019

182 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements