Problem
Section titled “Problem”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 = 2Output: ["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 = 4Output: ["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:
words[i]consists of lowercase English letters.kis in the range[1, The number of unique words[i]]
Follow-up: Could you solve it in time and extra space?
Solution approach
Section titled “Solution approach”Intuition
Section titled “Intuition”Count the words with a hash map. The answer order is a single ranking: word a beats word b if it is more frequent, or equally frequent and alphabetically smaller. Sorting all m distinct words by this rule costs ; the follow-up asks for .
To keep only the k best words, use a min-heap of size k whose top is the worst of the words kept so far. Push each distinct word; whenever the heap grows to k + 1, pop its top. A popped word is beaten by k other words, so it can never be in the answer. After all words are processed the heap holds exactly the top k, and popping it yields them from worst to best — reversing that gives the required order.
The comparator does the tie-breaking: with better(a, b) meaning “a beats b”, a heap built on better keeps the element that beats nobody — the worst — on top.
Algorithm
Section titled “Algorithm”- Count
freq[w]for every word. - For each
(word, count)infreq: push it intoheap; ifheap.size() > k, pop. - Pop the heap into
ans(worst first), then reverseans.
Walkthrough
Section titled “Walkthrough”Example 2 with k = 4: freq = {the: 4, is: 3, sunny: 2, day: 1}. Whatever order the map yields, the heap never exceeds four entries and nothing is popped, because there are exactly four distinct words. Popping gives day, sunny, is, the; reversed, ["the","is","sunny","day"].
For Example 1 with k = 2, freq = {i: 2, love: 2, leetcode: 1, coding: 1}. Each time a third word enters, the top is the worst word in the heap — a frequency-1 word, or between equal frequencies the alphabetically larger one — so both frequency-1 words are popped, and among i and love the heap returns love before i. Reversed: ["i","love"].
Complexity
Section titled “Complexity”Let n be the number of words and m the number of distinct words.
- Time: — counting is (word length is at most 10), and each of the
m <= npushes and pops costs . - Space: — the hash map holds
mwords; the heap and the answer hold at mostk + 1.
Edge cases
Section titled “Edge cases”- Ties at the cut-off: the comparator ranks equal counts alphabetically, so the alphabetically larger word is popped first, as required.
kequals the number of distinct words: nothing is ever popped during insertion; the heap simply sorts every word.
Think before you peek
Work out an approach on your own first — the explanation will still be here when you want it.
class Solution { public: vector<string> topKFrequent(vector<string>& words, int k) { unordered_map<string, int> freq; for (const string& w : words) freq[w]++;
// better(a, b): a ranks above b. The heap's top is therefore the worst word kept. auto better = [](const pair<int, string>& a, const pair<int, string>& b) { return a.first != b.first ? a.first > b.first : a.second < b.second; }; priority_queue<pair<int, string>, vector<pair<int, string>>, decltype(better)> heap(better);
for (auto& [word, count] : freq) { heap.push({count, word}); if ((int)heap.size() > k) heap.pop(); }
vector<string> ans; while (!heap.empty()) { ans.push_back(heap.top().second); heap.pop(); } reverse(ans.begin(), ans.end()); return ans; }};class Solution { public List<String> topKFrequent(String[] words, int k) { HashMap<String, Integer> freq = new HashMap<>(); for (String w : words) freq.merge(w, 1, Integer::sum);
// Order worst-first, so the heap's head is the worst word kept. PriorityQueue<Map.Entry<String, Integer>> heap = new PriorityQueue<>((a, b) -> !a.getValue().equals(b.getValue()) ? Integer.compare(a.getValue(), b.getValue()) : b.getKey().compareTo(a.getKey()));
for (var e : freq.entrySet()) { heap.offer(e); if (heap.size() > k) heap.poll(); }
LinkedList<String> ans = new LinkedList<>(); while (!heap.isEmpty()) ans.addFirst(heap.poll().getKey()); return ans; }}import heapqfrom collections import Counter
class Entry: """Heap entry; "less than" means "ranks below", so the heap's top is the worst word kept."""
__slots__ = ("count", "word")
def __init__(self, count, word): self.count, self.word = count, word
def __lt__(self, other): if self.count != other.count: return self.count < other.count return self.word > other.word
class Solution: def topKFrequent(self, words: list[str], k: int) -> list[str]: heap = [] for word, count in Counter(words).items(): heapq.heappush(heap, Entry(count, word)) if len(heap) > k: heapq.heappop(heap)
ans = [] while heap: ans.append(heapq.heappop(heap).word) ans.reverse() return ansGive it a try first
Attempt the problem on LeetCode — the code will still be here.