Top K Frequent Words

MediumHeapheap

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given a list of words words and an integer k, return the k words that appear most often. The result must be ordered by **frequency, highest first**. Words with the same frequency are ordered **alphabetically** (standard lexicographic order, so "ab" comes before "abc"). Each distinct word appears in the output at most once. k is between 1 and the number of distinct words. Try for O(n log k) time.

Examples

Input: words = ["apple","kiwi","apple","fig","kiwi","plum"], k = 2
Output: ["apple","kiwi"]
"apple" and "kiwi" both appear twice; alphabetical order puts "apple" first.
Input: words = ["red","blue","red","green","blue","red","gold","green","blue"], k = 3
Output: ["blue","red","green"]
"blue" and "red" appear 3 times ("blue" is alphabetically first), then "green" with 2.

Constraints

  • 1 <= words.length <= 500
  • 1 <= words[i].length <= 10
  • `words[i]` consists of lowercase English letters.
  • 1 <= k <= number of distinct words

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More heap problems