Top k most frequent elements

#include
#include
#include <unordered_map>
#include
using namespace std;

void Ktop(int *arr, int n, int k) {
vector top(k+1);
unordered_map<int, int> freq;
for(int m=0;m<n;m++) {
freq[arr[m]]++;
top[k] = arr[m];
auto it = find(top.begin(), top.end()-1, arr[m]);
for(int i=distance(top.begin(), it)-1;i>=0;i–) {
if(freq[top[i]]<freq[top[i+1]]) {
swap(top[i], top[i+1]);
} else if(freq[top[i]]==freq[top[i+1]] and top[i]>top[i+1]) {
swap(top[i], top[i+1]);
} else {
break;
}
}
for (int i = 0; i < k && top[i] != 0; ++i)
cout << top[i] << ’ ';
}

cout<<endl;

}
i tried but could not able to understand the code at all,can anyone please walk me through the code

@dare_devil_007 please share the code by saving it on cb ide and also share the source of this code.
Also, this question can be solved easily using a priority queue in O(n) time.

1 Like


Source :heap Lesson exercise Question
top k frequent elements in a stream of integers

i just did not get what was given in tutorial

@dare_devil_007 refer to this article the approach has been explained properly and the code is commented so you shouldnt have any trouble understanding it. Let me know if any doubt persists.

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.