Top K Frequent Words
Problem
Given an array of strings words and an integer k, return the k most frequent strings. Sort ties by lexicographical order (the word that comes first alphabetically ranks higher).
Examples
Example 1
Input: words = ["i","love","leetcode","i","love","coding"], k = 2
Output: ["i","love"]
Explanation: "i" and "love" both appear twice, tied — "i" and "love" are the two most frequent, order by frequency then alphabetically.
Constraints
- •
1 <= words.length <= 500 - •
1 <= k <= number of unique words
Hints
Hint 1
First count frequencies with a hash map — this part is a straightforward application of the frequency-map pattern.
Hint 2
The tie-breaking rule (lexicographical order among equal frequencies) needs to be encoded directly into the heap's comparator, not handled as an afterthought.
Hint 3
A min-heap of size k, evicting the 'worst' candidate (lowest frequency, or lexicographically largest on a tie) as you go, avoids sorting every unique word.
Solutions
public List<String> topKFrequentBruteForce(String[] words, int k) {
Map<String, Integer> freq = new HashMap<>();
for (String w : words) freq.merge(w, 1, Integer::sum);
List<String> uniqueWords = new ArrayList<>(freq.keySet());
uniqueWords.sort((a, b) ->
freq.get(a).equals(freq.get(b)) ? a.compareTo(b) : freq.get(b) - freq.get(a)
);
return uniqueWords.subList(0, k);
}Time: O(n log n) · Space: O(n)