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.
Function Signature
def top_k_frequent_words(words: list[str], k: int) -> list[str]:
Rules
-
The frequency of a word is the number of times it appears in
words
.
-
Each distinct word appears at most once in the output.
-
Words with equal frequency appear in ascending lexicographical order, so the expected output is unique.
Constraints
-
1 <= len(words) <= 500
-
1 <= len(words[i]) <= 10
-
words[i]
consists of lowercase English letters.
-
k
is between 1 and the number of unique words, inclusive.
Examples
Input: words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4
Output: ["the","is","sunny","day"]
The counts are the=4, is=3, sunny=2 and day=1. All four counts differ, so the output lists the words in descending order of count.
Input: words = ["apple","banana","apple","cherry","banana","date"], k = 3
Output: ["apple","banana","cherry"]
"apple" and "banana" both appear twice, and "apple" sorts first. "cherry" and "date" tie at one occurrence for the last slot, and "cherry" gets it because it comes before "date" alphabetically.