InterviewDryRun
Coding interview · Asked at mid level

Top K Frequent Words

How the interviewer asks it

“Given a list of words and a number k, return the k most frequent words, most frequent first. Words with the same count are ordered alphabetically.”
Sample test input
2
the day is sunny the the the sunny is is
Expected output
the
is

In the practice room your code reads the input from standard input, and Run checks it against tests like this one. Try it now in your browser, in Python or JavaScript.

Typed drills are free and unlimited: the AI scores your answer against the outline below.

What the interviewer is looking for

  • Counting with a hash map first, then choosing how to select the top k.
  • You compare options: full sort O(n log n), a min-heap of size k O(n log k), bucket sort O(n).
  • A correct comparator for the tie-break, which is where most bugs hide.
  • You know a min-heap of size k keeps the k largest, and that its order must be reversed at the end.

How to structure your answer

  1. 01

    Count

    One pass to build word → count.

  2. 02

    Pick a selection method

    Say the trade-offs, then pick a size-k min-heap ordered by count ascending and word descending, so the heap top is the worst of the current top k.

  3. 03

    Build the answer

    Push each entry, pop when the heap exceeds k, then pop everything and reverse.

  4. 04

    Test

    Include a tie at the boundary, for example two words with the same count competing for the last place.

  5. 05

    Complexity

    O(n log k) time and O(n) space for the counts.

Best answers from candidates

No candidate answers yet. Type yours, and if it scores 6 or more you can show it here without your name.

Answers are shared by candidates, without names, after a privacy check. Add yours

Common mistakes

  • Getting the tie-break backwards inside the min-heap, so alphabetically later words survive.
  • Sorting the whole map when k is tiny and n is huge, without mentioning the cost.
  • Forgetting to reverse the heap output.

Follow-up questions to expect

  • The words arrive as an endless stream. How do you keep an approximate top k? (Count-min sketch plus a heap.)
  • The data is spread across many machines.

Now answer it out loud

Max will ask you this exact question, listen to your answer, push on the weak spots with follow-ups like the ones above, and score you when you finish.

Practice with Max

Free: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.

More coding interview questions

Preparing for this round? Read how to prepare for a coding interview: a four-week DSA plan.