Algo-Sim › Heaps & Priority Queues
Top K Frequent Words
Medium · Heaps & Priority Queues · step through it in Java, Python and C++ on your own input
A size-k min-heap whose comparator puts fewer uses, then the alphabetically later word, on top, so the weakest is always the one evicted.
Problem
Given an array of strings words and an integer k, return the k most frequent words, most frequent first. Words with the same frequency are ordered alphabetically.
Constraints
- 1 ≤ words.length ≤ 500
- 1 ≤ words[i].length ≤ 10, lowercase letters
- 1 ≤ k ≤ the number of distinct words
Edge cases to test
- Ties broken alphabetically
- k equals the number of distinct words
- One word
Follow-up questions
- Why invert the tie-break inside a min-heap?
- The root must be the weakest word, so among equal counts the alphabetically larger one sits on top and is evicted first.
- What about bucket sort?
- Bucket words by count and sort each bucket alphabetically: O(n + m log m) in the worst case.
Solution
Java
public List<String> topKFrequent(String[] words, int k) {
Map<String, Integer> count = new LinkedHashMap<>();
for (String w : words) count.merge(w, 1, Integer::sum);
// The weakest of the k kept on top: fewer uses, or on a tie the later word.
PriorityQueue<String> heap = new PriorityQueue<>((a, b) -> count.get(a).equals(count.get(b)) ? b.compareTo(a) : count.get(a) - count.get(b));
for (String w : count.keySet()) {
heap.offer(w);
if (heap.size() > k) heap.poll();
}
List<String> result = new ArrayList<>();
while (!heap.isEmpty()) result.add(heap.poll());
Collections.reverse(result);
return result;
}Python
import heapq
from collections import Counter
class Entry:
# Heap order: fewer uses first; on a tie the alphabetically later word first.
def __init__(self, n, w):
self.n, self.w = n, w
def __lt__(self, other):
return self.n < other.n if self.n != other.n else self.w > other.w
def top_k_frequent(words, k):
count = Counter(words)
heap = [] # the k best so far, the weakest on top
for w, n in count.items():
heapq.heappush(heap, Entry(n, w))
if len(heap) > k:
heapq.heappop(heap)
result = []
while heap:
result.append(heapq.heappop(heap).w)
return result[::-1]C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<string> topKFrequent(vector<string> &words, int k) {
unordered_map<string, int> count;
vector<string> order;
for (auto &w : words)
if (count[w]++ == 0)
order.push_back(w);
// The weakest of the k kept on top: fewer uses, or on a tie the later word.
auto weaker = [&](const string &a, const string &b) { return count[a] != count[b] ? count[a] > count[b] : a < b; };
priority_queue<string, vector<string>, decltype(weaker)> heap(weaker);
for (auto &w : order) {
heap.push(w);
if (int(heap.size()) > k)
heap.pop();
}
vector<string> result;
while (!heap.empty()) {
result.push_back(heap.top());
heap.pop();
}
reverse(result.begin(), result.end());
return result;
}
};
More Heaps & Priority Queues problems
- Kth Largest Element in an Array (Medium)
- Kth Largest Element in a Stream (Easy)
- Merge K Sorted Lists (Hard)
- Find Median from Data Stream (Hard)
- Find K Pairs with Smallest Sums (Medium)
- Heap Sort (Build Heap + Sift Down) (Medium)
- Last Stone Weight (Easy)
- K Closest Points to Origin (Medium)
- Reorganize String (Medium)
- IPO (Hard)