Intuition
Count word frequencies, then order candidates by frequency descending and, for ties, lexicographically ascending; take the first k.
Explanation
Count + custom order
Build a frequency map, then sort the unique words by the key (-frequency, word) so higher counts come first and equal counts break alphabetically. Return the first k.
count = Counter(words)
return sorted(count, key=lambda w: (-count[w], w))[:k]
(A size-k heap with the same comparator does it in O(n log k).)
Worked example
["i","love","python","i","love","coding"], k=2 → ["i","love"] (both freq 2, 'i' < 'love').
Complexity
- Time: O(n log k).
- Space: O(n).
Implementation
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Solution {
public List<String> topKFrequent(String[] words, int k) {
Map<String, Integer> count = new HashMap<>();
for (String w : words) count.merge(w, 1, Integer::sum);
List<String> res = new ArrayList<>(count.keySet());
res.sort((a, b) -> count.get(a).equals(count.get(b))
? a.compareTo(b)
: count.get(b) - count.get(a));
return res.subList(0, k);
}
}