Skip to content
BytePatterns

K Most Frequent Words

MediumTwo Heaps & K-Way Merge#top-k#min-heap#hash-map~20m

Problem

Given a list of words and an integer k, return the k words that occur most often, from most to least frequent. Words with the same count are ordered alphabetically, so the answer is always unique. k is at most the number of distinct words.

Examples

Input:  words = ["red", "blue", "red", "green", "blue", "red"], k = 2
Output: ["red", "blue"]
Why:    red appears 3 times, blue 2 and green 1
Input:  words = ["b", "a", "c", "a", "b", "c"], k = 2
Output: ["a", "b"]
Why:    all three words appear twice, so the alphabetical tie-break picks a and b
Input:  words = ["solo"], k = 1
Output: ["solo"]
Why:    edge case, a single word is its own top 1

Hints

0 / 3

Stuck on the idea rather than the code? Top K in a Stream covers it.