Problem
Return the k most frequent words in a list. If two words have the same frequency, the lexicographically smaller word comes first. The answer should be ordered by frequency descending, then by the lexical rule.
Original: LeetCode 692: Top K Frequent Words.
Examples
Example 1
`words = ["i", "love", "leetcode", "i", "love", "coding"], k = 2``["i", "love"]`Both appear twice; "i" comes first alphabetically.
Example 2
`words = ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4``["the", "is", "sunny", "day"]`Constraints
1 <= words.length <= 5001 <= words[i].length <= 10words[i]consists of lowercase English letters.kis in the range[1, The number of unique words[i]]
Hints
Hint 1
The tie-break is on the word itself, not on insertion order. Words are lowercase in the official tests.
Hint 2
Top-k by frequency is a heap, but the comparator must encode the lexical rule.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Count, sort every unique word by (-count, word), and take the first k.
Optimal. A size-k min-heap whose "smaller" element is the one that should be evicted first: lower frequency, or the same frequency and a lexicographically larger word. A full sort of the unique words is simpler and often fast enough.
Alternative. Bucket lists of words by frequency, then sort only the buckets you need, from high frequency down.
Complexity
- Time
- O(n + m log k)
Counting is O(n). The heap is O(m log k), where m is the number of unique words, plus O(k log k) to emit the answer. A full sort of the unique words is O(m log m).
- Space
- O(m + k)
Code
import heapq
from collections import Counter
class NegStr:
def __init__(self, s: str) -> None:
self.s = s
def __lt__(self, other: "NegStr") -> bool:
return self.s > other.s # reverse lexical: larger word is "smaller" in the heap
def top_k_frequent(words: list[str], k: int) -> list[str]:
count = Counter(words)
heap: list[tuple[int, NegStr]] = []
for w, c in count.items():
heapq.heappush(heap, (c, NegStr(w)))
if len(heap) > k:
heapq.heappop(heap)
return [w.s for _, w in sorted(heap, key=lambda t: (-t[0], t[1].s))]
if __name__ == "__main__":
assert top_k_frequent(["i", "love", "leetcode", "i", "love", "coding"], 2) == ["i", "love"]
assert top_k_frequent(["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], 4) == ["the", "is", "sunny", "day"]
print("ok")import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.PriorityQueue;
public class TopKFrequentWords {
static List<String> topKFrequent(String[] words, int k) {
var count = new HashMap<String, Integer>();
for (var w : words) count.merge(w, 1, Integer::sum);
var heap = new PriorityQueue<String>((a, b) -> {
int cmp = Integer.compare(count.get(a), count.get(b));
return cmp != 0 ? cmp : b.compareTo(a);
});
for (var w : count.keySet()) {
heap.offer(w);
if (heap.size() > k) heap.poll();
}
var ans = new ArrayList<String>();
while (!heap.isEmpty()) ans.add(heap.poll());
Collections.reverse(ans);
return ans;
}
public static void main(String[] args) {
var a = topKFrequent(new String[] {"i", "love", "leetcode", "i", "love", "coding"}, 2);
if (!a.equals(List.of("i", "love"))) throw new AssertionError(a);
var b = topKFrequent(new String[] {"the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"}, 4);
if (!b.equals(List.of("the", "is", "sunny", "day"))) throw new AssertionError(b);
System.out.println("ok");
}
}Edge cases
- Official samples: ["i","love","leetcode","i","love","coding"] with k = 2 returns ["i","love"]; ["the","day","is","sunny","the","the","the","sunny","is","is"] with k = 4 returns ["the","is","sunny","day"].
- On a tie, the lexicographically smaller word ranks higher, so it must stay in the heap when frequencies are equal.
Follow-ups
- Top K Frequent Elements uses a numeric tie-break, or no tie-break at all, so the comparator is simpler.
Interview script
"I count frequencies, then I keep a min-heap of size k. The eviction order is lower frequency first, and on a tie the lexicographically larger word is weaker. I reverse the heap at the end so the answer is sorted the way the problem asks."
Source: LeetCode 692: Top K Frequent Words Source: Java SE 17 API: PriorityQueue
Multiway merge and pair selection
Sources (2)
- LeetCode 692: Top K Frequent Wordsleetcode.com
- Java SE 17 API: PriorityQueuedocs.oracle.com