SDE & MLE Prep

692. Top K Frequent Words

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))