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
words: string[], k: intstring[]Examples
words = ["i","love","leetcode","i","love","coding"], k = 2 returns ["i","love"].words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4 returns ["the","is","sunny","day"].words = ["Apple","apple","Banana","banana","Apple","banana","Cherry","apple","banana","Cherry","Cherry"], k = 3 returns ["Cherry","banana","Apple"].Constraints
1 <= words.length <= 1000001 <= words[i].length <= 1001 <= k <= the number of distinct words in wordsFollow-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?