DSA Trie

Top K Frequent Words

Return the k most frequent words, ties broken lexicographically — counter + heap.

Medium
Time O(N log k) Space O(N)
LeetCode
6 min read
hash-map heap sorting

Problem#

Given an array of words and integer k, return the k most frequent words. Sort by frequency descending; on ties, sort alphabetically.

Examples#

  • words = ["i","love","leetcode","i","love","coding"], k = 2["i","love"].
  • words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4["the","is","sunny","day"].

Constraints#

  • 1 <= words.length <= 500, 1 <= words[i].length <= 10.

Hints#

Hint
Min-heap of size k with comparator: higher freq is “smaller”, and within equal freq, larger string is “smaller”.

Approach#

Count occurrences with a hash map. Maintain a size-k min-heap whose ordering inverts the desired output so the “worst” element is at top — when the heap exceeds k, pop. Drain the heap at the end and reverse.

Solution#

Top K Frequent Words
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string, int> cnt;
for (auto& w : words) ++cnt[w];
auto cmp = [](const pair<int,string>& a, const pair<int,string>& b) {
if (a.first != b.first) return a.first > b.first; // smaller freq sits at top
return a.second < b.second; // larger word sits at top
};
priority_queue<pair<int,string>, vector<pair<int,string>>, decltype(cmp)> pq(cmp);
for (auto& [w, c] : cnt) {
pq.push({c, w});
if ((int)pq.size() > k) pq.pop();
}
vector<string> ans(k);
for (int i = k - 1; i >= 0; --i) { ans[i] = pq.top().second; pq.pop(); }
return ans;
}
};

Editorial#

The comparator’s two-axis inversion ensures pop() always removes the candidate that loses the tie. Heap of size k keeps memory at O(k); total operations are N log k. For exact tie ordering, the lexicographic comparison on string matches the spec exactly.

Complexity#

  • Time: O(N log k).
  • Space: O(N) for the counter.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.