Top K Frequent Words
medium
hash-map
heap
sorting
strings
Given an array of strings words and an integer k, return the k most frequent words.
The output order is part of the problem definition: you MUST rank words by frequency descending, and when two words have the same frequency, you MUST break ties by lexicographic (dictionary) ascending order. Use exact case-sensitive string comparison for that tie-break, so every correct solution returns the same deterministic array whether it uses sorting, a heap, or another approach.
Input / output
- Input:
words: string[],k: int - Output:
string[]
Examples
words = ["i","love","leetcode","i","love","coding"],k = 2returns["i","love"].words = ["the","day","is","sunny","the","the","the","sunny","is","is"],k = 4returns["the","is","sunny","day"].words = ["Apple","apple","Banana","banana","Apple","banana","Cherry","apple","banana","Cherry","Cherry"],k = 3returns["Cherry","banana","Apple"].
Constraints
1 <= words.length <= 1000001 <= words[i].length <= 1001 <= k <=the number of distinct words inwords- Words may repeat.
- Comparisons are case-sensitive.
Follow-up
If there are m distinct words, can you improve a full O(m log m) ranking into O(m log k) after counting frequencies by keeping only the current best k candidates in a heap?
Examples
Example 1
Input: words = ["i","love","leetcode","i","love","coding"], k = 2
Output: ["i","love"]
Example 2
Input: words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4
Output: ["the","is","sunny","day"]