#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <queue>
#include <algorithm>
using namespace std;
class node {
public:
string word;
int count;
node(string w, int c) {
word = w;
count = c;
}
};
class comp {
public:
bool operator()(node a, node b) {
if (a.count == b.count) {
return (a.word > b.word); // Lexicographically smaller first
}
return (a.count < b.count); // Higher frequency first
}
};
vector<string> kMostFreqWords(string words[], int n, int k) {
// Step 1: Frequency counting
unordered_map<string, int> mp;
for (int i = 0; i < n; i++) {
mp[words[i]]++;
}
// Step 2: Maintain a max-heap
priority_queue<node, vector<node>, comp> pq;
for (auto& entry : mp) {
pq.push(node(entry.first, entry.second));
}
// Step 3: Extract the top k elements
vector<string> ans;
while (k-- && !pq.empty()) {
node topNode = pq.top();
pq.pop();
ans.push_back(topNode.word);
}
return ans;
}


