692. Top K Frequent Words
Asked at 21Bloomberg45Amazon44Google33Apple30Meta28Microsoft23Robinhood100tcs27Box100Pocket Gems100Zynga100Yelp94Adobe63Palo Alto Networks59Uber57PayPal51Rippling46Nvidia39Salesforce35Oracle35Goldman Sachs21
Problem
Return the k most frequent words, ordered by frequency from highest to lowest; words with equal frequency go in lexicographic order.
Example: words = ["i","love","leetcode","i","love","coding"], k = 2 → ["i","love"]
Constraints: follow-up: O(n log k) time.
Count, then order by (−count, word). A size-k heap needs the reverse order (min count, then larger word evicted first).
Complexity: O(n log k).
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
cnt = Counter(words)
return heapq.nsmallest(k, cnt, key=lambda w: (-cnt[w], w))
assert Solution().topKFrequent(["i", "love", "leetcode", "i", "love", "coding"], 2) == ["i", "love"]
assert Solution().topKFrequent(["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], 4) == ["the", "is", "sunny", "day"]
class Solution {
public List<String> topKFrequent(String[] words, int k) {
Map<String, Integer> cnt = new HashMap<>();
for (String w : words) cnt.merge(w, 1, Integer::sum);
// min-heap whose top is the "worst": lowest count, then lexicographically largest
PriorityQueue<String> pq = new PriorityQueue<>((a, b) ->
cnt.get(a).equals(cnt.get(b)) ? b.compareTo(a) : cnt.get(a) - cnt.get(b));
for (String w : cnt.keySet()) {
pq.add(w);
if (pq.size() > k) pq.poll();
}
LinkedList<String> res = new LinkedList<>();
while (!pq.isEmpty()) res.addFirst(pq.poll());
return res;
}
}
func topKFrequent(words []string, k int) []string {
cnt := map[string]int{}
for _, w := range words {
cnt[w]++
}
keys := make([]string, 0, len(cnt))
for w := range cnt {
keys = append(keys, w)
}
sort.Slice(keys, func(i, j int) bool { // by count desc, then alphabetically
a, b := keys[i], keys[j]
if cnt[a] != cnt[b] {
return cnt[a] > cnt[b]
}
return a < b
})
return keys[:k]
}