The Top Words

A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
medium
Seniority
L4
Asked in
LinkedIn

Problem

Given a text string and integer k, split on whitespace, count occurrences, and return the k words with the highest counts. Sort by count descending, tie-break alphabetically ascending. If fewer than k distinct words exist, return all of them.

In every document, some words dominate the conversation.

Example 1

Input:

text = "the day is sunny the day is is bright", k = 4

Output:

["is","day","the","bright"]

Example 2

Input:

text = "i love data and data loves me", k = 2

Output:

["data","and"]

Worked solution and explanation

Why this problem exists in real interviews

This tests frequency counting combined with custom sorting (by count descending, then alphabetically for ties). It mirrors the common data pipeline pattern of ranking items by a metric with tiebreaker rules.


Break down the requirements

Step 1: Split text and count word frequencies

Split on whitespace and accumulate counts in a dict.

Step 2: Sort by frequency descending, then alphabetically for ties

Use a composite sort key: negate the count for descending order, use the word itself for alphabetical tiebreaking.

Step 3: Return the top k words

Slice the sorted list to the first k entries.


The solution

Frequency sort with alphabetical tiebreaker
def top_k_words(text: str, k: int) -> list:
    words = text.split()
    freq = {}
    for word in words:
        freq[word] = freq.get(word, 0) + 1
    sorted_words = sorted(freq.keys(), key=lambda w: (-freq[w], w))
    result = []
    for i in range(min(k, len(sorted_words))):
        result.append(sorted_words[i])
    return result

Common follow-up questions