Top K Frequent Words
Find the k most frequent words using sorting vs a min-heap with custom ordering.
Top K Frequent Words
Problem: Given an array of words and an integer k, return the k most frequent words. If two words have the same frequency, return them in alphabetical order. The result must be sorted by frequency (highest first).
Example:
- Input:
words = ["i","love","leetcode","i","love","coding"],k = 2 - Output:
["i","love"]— "i" appears 2×, "love" appears 2×, both tied but "i" < "love" alphabetically
Note
The twist compared to Top K Frequent Elements: when frequencies are equal, alphabetically smaller words rank higher. Your comparator must handle both dimensions.
Brute Force
View Brute Force
Optimal — Min-Heap of Size k
View Optimal Solution
| Approach | Time | Space |
|---|---|---|
| Count + Sort | O(n log n) | O(n) |
| Count + Min-Heap | O(n log k) | O(n) |