Skip to content

3. Top K Frequent Words

Difficulty: Easy · Topic: Core Python & data structures

Write top_words(text, k): the k most frequent words of text as a list of (word, count) tuples, most frequent first.

Your code runs in CPython on our servers against 6 tests, including hidden ones.

Sample test

top_words("the cat and the hat and the bat", 2)

Expected: [('the', 3), ('and', 2)]

Hints

Hint 1collections.Counter(words) counts everything in one pass.
Hint 2Counter.most_common(k) breaks ties by first appearance, not alphabetically, so sort yourself.
Hint 3Sort by a tuple key: key=lambda kv: (-kv[1], kv[0]) puts higher counts first, then words A to Z.

Learn the concepts

More Python problems

All Python problems