📘
Top K Frequent Words
MediumHeap / Priority Queue
Given a list of words and integer k, return the k most frequent words sorted by frequency (descending), then alphabetically for ties.
Output one word per line.
Example:
Input:
i,love,leetcode,i,love,coding 2
Output:
i love
Reasoning:
- The input string is split into a list of words:
['i', 'love', 'leetcode', 'i', 'love', 'coding'] - The frequency of each word is calculated:
{'i': 2, 'love': 2, 'leetcode': 1, 'coding': 1} - The words are sorted by frequency in descending order, then alphabetically for ties:
['i', 'love', 'coding', 'leetcode'] - The top k=2 words are selected from the sorted list and output one per line:
iandlove
Constraints:
- 1 <= len(words) <= 500
- 1 <= k <= number of unique words
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.