Skip to main content

Given a block of text, return the k most frequent words with their counts. For example, for "the cat sat, the cat ran, the end" and k = 2, return "the" with 3 and "cat" with 2.

Coding rounds · Intermediate 1

Short answer

Lower-case the text, split it into words with a regular expression, count with collections.Counter and call most_common(k). Counting is O(n) time for n words and O(u) memory for u unique words. most_common(k) uses a heap, so it costs about O(u log k) and does not sort everything.

Deeper answer

First clarify what a word is. Ask whether case matters, whether punctuation should be removed, and whether "don't" is one word. Ask how large the text is and what to return when k is larger than the number of unique words.

Then say the steps. Extract words with re.findall(r"[a-z']+", text.lower()), which lower-cases the text, drops punctuation and keeps apostrophes. Count and rank in one line: Counter(words).most_common(k). Without Counter, use a dict with counts[word] = counts.get(word, 0) + 1 and then sorted(counts.items(), key=lambda item: -item[1])[:k].

Counting is O(n). A full sort is O(u log u), where u is the number of unique words. Test empty text, k of zero, ties and text with only punctuation. Say that most_common keeps first-seen order for ties, and ask if ties need alphabetical order. For a very large file, read line by line and update the same Counter.

What a strong answer covers

Answer it out loud in the mock interview about 2.5 min

Follow-ups to expect

Common mistakes

Learn it

Lists and dictionaries

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.