Top K Words

Python data engineering interview problem. Difficulty: beginner. Pattern: Heaps. About 10 minutes. Free to practice.

Return the k most frequent words with tie-break by lexicographic order. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.

A search engine, a news site or a log tool often wants the most popular words. Here you will find the k words that appear most often in a list. Write a function top_k_words(words, k) that takes a list of words and a number k, and returns the k most frequent words. The most frequent word comes first. If 2 words appear the same number of times, the one that comes first in the dictionary (alphabetical order) goes first. For ['i', 'love', 'leetcode', 'i', 'love', 'coding'] and k = 2, i and love both appear twice, and i comes before love alphabetically, so the answer is ['i', 'love']. Keep the print lines in the editor.

Requirements

  • Count how many times each word appears.
  • Return exactly k words.
  • Sort the words by count from high to low.
  • When 2 words have the same count, put the alphabetically smaller word first.

Constraints

  • 1 <= k <= number of unique words, so there are always at least k different words.
  • Return a list of words only, without the counts.
  • Words are compared exactly as written, so 'Love' and 'love' are different.

Examples

Input: top_k_words(['i','love','leetcode','i','love','coding'], 2) Output: ['i', 'love'] i and love both appear twice; leetcode/coding once.

Topics: lakebench, python, heap, frequency.

More Python interview questions · All interview problems · Learn data engineering

beginner

Top K Words

Interview-style drill: Return the k most frequent words with tie-break by lexicographic order.

Implement `top_k_words(words: list[str], k: int) -> list[str]` returning the k most frequent words. Ties break by lexicographically smaller word first. Example: `['i','love','leetcode','i','love','coding'], 2` → `['i','love']`. Keep the harness.