LeetCode Problem 692.
Given an array of strings words and an integer k, return the k most frequent strings.
Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order.
Example 1:
Input: words = ["i","love","leetcode","i","love","coding"], k = 2
Output: ["i","love"]
Explanation: "i" and "love" are the two most frequent words.
Note that "i" comes before "love" due to a lower alphabetical order.
Example 2:
Input: words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4
Output: ["the","is","sunny","day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.
Constraints:
First count how often each word appears with a hash map. Then we need the k "best" words, where a word is better if it appears more often, or, at the same count, if it comes first alphabetically.
Sorting all distinct words would take O(n log n). To meet the follow-up's O(n log k), keep a heap that holds at most k words, with the worst word on top:
k words, pop the top. That removes the worst word, which cannot be in the answer.k best words. Popping them gives worst to best, so reverse that order.The only tricky part is the comparison. "Worst" means a lower count, or, at the same count, the word that is later alphabetically. With words = ["a", "b", "a"] and k = 1, the heap compares ("a", 2) with ("b", 1) and drops "b".
Complexity: O(n log k) time, where n is the number of words: counting is O(n), and each heap operation is O(log k). O(n) space for the counts.
import heapq
from collections import Counter
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
counts = Counter(words)
# nsmallest keeps a heap of only k items: O(n log k).
# Sort key: higher count first, then alphabetical order.
return heapq.nsmallest(k, counts.keys(), key=lambda word: (-counts[word], word))
No runs yet.