PIXELBANKv8.2.1
Menu

Top K Frequent Words

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=2k = 2 words are selected from the sorted list and output one per line: i and love

Constraints:

  • 1 <= len(words) <= 500
  • 1 <= k <= number of unique words
Editor

Test Results

0/0
Run code to see test results.