Top K Frequent Words in C++

C++Server Side ProgrammingProgramming

Suppose we have a non-empty list of words; we have to find the k most frequent elements. our answer should be sorted by frequency from highest to lowest. When two words have the same frequency, then the word with the lower alphabetical order will be placed at first. So if the array is like [‘the’, ‘sky’, ‘is’, ‘blue’, ‘the’, ‘weather’, ‘is’, ‘comfortable’], so most frequent words are ["is","the","blue"]

To solve this, we will follow these steps −

  • Define one map called m
  • create one priority queue v
  • for i := 0 to n, where n is the size of the word array, then increase m[words[i]] by 1
  • for each element e in map
    • if size of v < k, then insert e into v
    • otherwise if value of is < value of e, then delete top element from v and insert e into v.
    • otherwise if value of is = value of e and key of is > key of e, then delete top element from v, insert e into the v
  • define one array called res
  • while v is not empty,
    • temp := top of v
    • delete top from v
    • insert key of temp into the res array
  • reverse the res array
  • return res


Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   cout << "]"<<endl;
struct Comparator{
   bool operator()(pair <string ,int> a, pair <string, int> b){
      if(a.second != b.second) return !(a.second < b.second);
         return !(a.first > b.first);
class Solution {
   static bool cmp(pair <string, int> a, pair <string, int> b){
      if(a.second != b.second) return a.second > b.second;;
         return a.first < b.first;
   vector<string> topKFrequent(vector<string>& words, int k) {
      map<string, int> m;
      priority_queue < pair <string, int>, vector < pair <string, int> >, Comparator > v;
      for(int i = 0; i < words.size(); i++){
      map<string, int> :: iterator i = m.begin();
      while(i != m.end()){
         if(v.size() < k){
         else if( < i->second){
         else if( == i->second && > i->first){
      vector <string> res;
         pair <string, int> temp =;
      reverse(res.begin(), res.end());
      return res;
   Solution ob;
   vector<string> v = {"the", "sky", "is", "blue", "the", "weather", "is", "comfortable"};
   print_vector(ob.topKFrequent(v, 3));


["the", "sky", "is", "blue", "the", "weather", "is", "comfortable"]


Published on 27-Feb-2020 10:36:20