Leetcode 692. Top K Frequent Words
Given an array of strings words
and an integer k
, return the k
most frequent strings.
The answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.
words
array?Assuming:
words
can be up to (10^4).unordered_map
) to count the frequency of each word.k
elements.k
, the smallest element (i.e., least frequent or lexicographically larger in case of tie) is popped out.Here’s how you can implement this in C++:
#include <vector>
#include <string>
#include <unordered_map>
#include <queue>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string, int> count;
for (const string& word : words) {
count[word]++;
}
auto comp = [](pair<int, string>& a, pair<int, string>& b) {
if (a.first == b.first)
return a.second > b.second;
return a.first < b.first;
};
priority_queue<pair<int, string>, vector<pair<int, string>>, decltype(comp)> pq(comp);
for (const auto& entry : count) {
pq.push({entry.second, entry.first});
if (pq.size() > k) {
pq.pop();
}
}
vector<string> result;
while (!pq.empty()) {
result.push_back(pq.top().second);
pq.pop();
}
reverse(result.begin(), result.end());
return result;
}
};
This approach ensures we efficiently maintain the top k
frequent words and return them in the desired order.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?