# Write a program in C++ to find the top K frequent element in an array of integers

C++Server Side ProgrammingProgramming

Suppose we have an array of integers of size N and a key K. Our task is to print the top K most frequent element of the array. For example,

Input-1

N = 6
K = 2
arr[ ] = {1 ,1, 1, 2, 2, 3}

Output

1 2

Explanation − In the given array of integers, the top K=2 elements whose frequency is most in the array are {1,2}.

Input-2

N = 2
K = 1
arr[ ] = {1, 2}

Output

1

Explanation − In the given array of integers, the top K=1 elements whose frequency is most in the array are {1}.

## Approach to solve this problem

In the given array of integers, we have to find and return those numbers which are repeating most of the time in the given array. The key K shows the top K element of the array which we have to return while traversing the array.

The approach is very simple. We will create a hash table with a key as the current element and a value as an occurrence of that particular number. After sorting the whole map and finding the occurrences of each of the elements, return the output result of the first K most frequent elements.

• Take N as Input and the array of N elements.

• A function topKfrequent(int *arr, int k) that takes an arr[ ] and the key K as Input and returns the top K frequent elements.

• Create a hashmap of all the elements and their occurrences as a key and pair.

• Sort all the values in the hashmap.

• A bool helper function helps to sort the map by values and returns the values in descending order.

• Iterate over all the values in the hashmap and return the top K most frequent element in the given array.

## Example

#include<bits/stdc++.h>
using namespace std;
bool compare(pair<int,int>&a, pair<int,int>&b){
return a.second>b.second;
}
void topKfrequent(int arr,int n, int k){
unordered_map<int,int>mp;
for(int i=0;i<n;i++){
mp[nums[i]]++;
}
vector<pair<int,int>>v(mp.begin(),mp.end());
sort(v.begin(),v.end(),compare);
for(int i=0;i<k;i++){
cout<<v[i].first<< " ";
}
}
int main(){
int N= 5;
int arr[N]= {1,1,3,2,2};
int k=2;
topKfrequent(arr,k);
return 0;
}

## Output

Running the above code will generate the following output,

2 1

In the given array of integers, the top K=2 most frequent elements are 2, 1.