easy +10 pts

Top K Frequent Words

Sort words by frequency and alphabetically to return the top K.

Write a function `top_k_frequent(words, k)` that takes a list of lowercase words and an integer k, and returns a list of the k most frequent words. The result must be sorted by frequency from highest to lowest. If two words have the same frequency, the alphabetically smaller word should come first. You may assume that k is positive and less than or equal to the number of unique words.

Constraints

1 <= len(words) <= 10^4 1 <= k <= number of unique words Each word consists of lowercase English letters.

Example

>>> top_k_frequent(["i","love","leetcode","i","love","coding"], 2)
['i', 'love']
>>> top_k_frequent(["the","day","is","sunny","the","the","the","sunny","is","is"], 4)
['the', 'is', 'sunny', 'day']
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Count the frequency of each word using a dictionary.
Sort the unique words using a key that primarily uses negative frequency and then the word itself.
Slice the sorted list to keep only the first k words.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.