Top K Frequent Words
MediumHash Map · Databricks
You are given a list of strings words and an integer k. Return the k most frequent words.
The result must be sorted by frequency from highest to lowest. Words with the same frequency are ordered alphabetically (lexicographically ascending, so "ab" comes before "b" and "a" before "ab"). When frequencies tie at the cut-off, this same ordering decides which words make it into the top k.
Each word appears at most once in the result.
Example 1
- Input:
- words = ["kafka", "spark", "delta", "spark", "kafka", "airflow"], k = 3
- Output:
- ["kafka", "spark", "airflow"]
- Explanation
kafkaandsparkboth appear twice, so they come first, in alphabetical order.airflowanddeltaboth appear once; only one more word fits, andairflowwins the tie alphabetically.
Example 2
- Input:
- words = ["b", "a", "b", "c", "a", "b"], k = 2
- Output:
- ["b", "a"]
- Explanation
bappears 3 times andatwice, so the answer is["b", "a"]. Frequency comes before alphabetical order.
Example 3
- Input:
- words = ["ab", "a", "ab", "a"], k = 2
- Output:
- ["a", "ab"]
- Explanation
- Both words appear twice.
"a"is a prefix of"ab", so it comes first alphabetically.
Constraints
- 1 ≤
words.length≤ 500 - 1 ≤
words[i].length≤ 10 words[i]consists of lowercase English letters- 1 ≤
k≤ the number of distinct words