Top K Frequent Words
Medium
Topics
Given an array of strings words and an integer k, return the k most frequent words.
The result is sorted by frequency, highest first. Words that occur the same number of times are ordered alphabetically, which makes the answer unique.
Example 1
k = 2 takes the first 2. The ordering runs by count from the highest down. Where counts are equal the alphabet settles it, which is why i precedes love — both occur 2 times and nothing else could separate them.Input: words = ["i","love","leetcode","i","love","coding"], k = 2 Output: ["i","love"] Explanation: Both occur twice, and "i" sorts before "love".
Example 2
Input: words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4 Output: ["the","is","sunny","day"] Explanation: Counts are 4, 3, 2, 1, so no tie-break is needed.
Example 3
Input: words = ["a","b","c"], k = 3 Output: ["a","b","c"] Explanation: Every word occurs once, so the whole answer is decided alphabetically.
Constraints
- 1 <= words.length <= 500
- 1 <= words[i].length <= 10
- words[i] consists of lowercase English letters
- 1 <= k <= number of distinct words
Editorial — intuition, approach, complexity and pitfalls
Intuition
Counting is the easy half. The half that decides whether an answer is accepted is the ordering, because the two keys run in opposite directions: count descending, but word ascending. Sorting by one and then reversing gets the second key backwards.
The clean way to say it is a single comparison that returns "a before b" when a has the larger count, and falls through to the plain string comparison when the counts are equal. Expressed as a sort key in Python that is (-count, word), which gets both directions right at once.
If k is much smaller than the number of distinct words, a full sort does more work than needed and a size-k container suffices. The subtlety is that such a container has to discard the worst element, so its comparison is the inverse of the one above — and inverting a two-key comparison means flipping both keys, not just the count.
That inversion is where this problem actually bites. A container ordered by "smallest count first" will, among equal counts, want the alphabetically largest word at the top so it can throw that one away.
Approach
- Count occurrences of each word.
- Sort the distinct words by count descending, then by the word ascending, and take the first
k. - For the size-limited variant: keep a container of at most
kentries ordered worst-first, meaning smallest count, and among equal counts the alphabetically largest word. Push each distinct word, and whenever the size exceedsk, drop the top. - Reverse what remains to get best-first order, since the container held them worst-first.
Walkthrough
words = ["the","day","is","sunny","the","the","the","sunny","is","is"]
k = 4
counts
the 4
is 3
sunny 2
day 1
sort key (-count, word)
the (-4, "the")
is (-3, "is")
sunny (-2, "sunny")
day (-1, "day")
answer: the is sunny day
now a case where the tie-break matters
words = ["i","love","leetcode","i","love","coding"], k = 2
i 2
love 2
coding 1
leetcode 1
keys: i (-2,"i"), love (-2,"love")
equal counts, so "i" < "love" decides it
answer: i love NOT love iComplexity
- Time — O(n + d log d): counting is linear in the input; the sort is over the d distinct words.
- Space — O(d): one entry per distinct word.
Common Pitfalls
- Sorting by count ascending and reversing. That reverses the alphabetical key too, so tied words come out backwards.
- Comparing word lengths instead of the words themselves. The tie-break is dictionary order, so
"zoo"comes after"apple". - Using a size-
kcontainer with the same comparison as the final sort. It has to be inverted, and inverting means flipping both keys. - Returning counts alongside the words. The answer is the words only.
- Assuming
kcan exceed the number of distinct words. It cannot, so no padding case is needed.
Full Solution — all languages
class Solution:
def topKFrequent(self, words, k):
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
# Count descending, word ascending. Negating the count lets one
# ascending sort express both directions at once.
ordered = sorted(counts, key=lambda w: (-counts[w], w))
return ordered[:k]import java.util.*;
class Solution {
public List<String> topKFrequent(String[] words, int k) {
Map<String, Integer> counts = new HashMap<>();
for (String w : words) counts.merge(w, 1, Integer::sum);
List<String> distinct = new ArrayList<>(counts.keySet());
distinct.sort((x, y) -> {
int byCount = counts.get(y) - counts.get(x); return byCount != 0 ? byCount : x.compareTo(y);
})
;
return distinct.subList(0, Math.min(k, distinct.size()));
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string, int> counts;
for (const string& w : words) counts[w]++;
vector<string> distinct;
for (auto& kv : counts) distinct.push_back(kv.first);
sort(distinct.begin(), distinct.end(), [&](const string& x, const string& y) {
if (counts[x] != counts[y]) return counts[x] > counts[y]; return x < y;
})
;
distinct.resize(min((size_t)k, distinct.size()));
return distinct;
}
};/**
* @param {string[]} words
* @param {number} k
* @return {string[]}
*/ var topKFrequent = function(words, k) {
const counts = new Map();
for (const w of words) counts.set(w, (counts.get(w) || 0) + 1);
return [...counts.keys()] .sort((x, y) => (counts.get(y) - counts.get(x)) || (x < y ? -1 : (x > y ? 1 : 0))) .slice(0, k);
};