Rank the K Most Repeated Words in a Document

Implement topRepeatedWords

Given the words of a document, return the k words that appear most often, ranked from most to least frequent. When two words appear the same number of times, the alphabetically earlier word ranks higher.

Sorting every distinct word gives the answer but orders words that can never make the cut. A size-k heap that keeps the worst-ranked candidate at its root lets each word be judged with a single O(log k) push and, when the heap overflows, a single eviction.

Example 1:

Input: words = ["pear","fig","pear","kiwi","fig","pear","kiwi","date"], k = 2

Output: ["pear","fig"]

Example 2:

Input: words = ["b","a","b","a"], k = 1

Output: ["a"]

Example 3:

Input: words = ["ab","abc","ab","abc","a"], k = 3

Output: ["ab","abc","a"]

+ 10 hidden test cases run on Submit.

Constraints:

  • ●1 ≤ words.length ≤ 100
  • ●Each word is 1 to 10 lowercase English letters
  • ●1 ≤ k ≤ the number of distinct words in the document
  • ●Rank by how many times a word appears (highest first); words that appear equally often are ranked alphabetically (a before b)

words =

["pear", "fig", "pear", "kiwi", "fig", "pear", "kiwi", "date"]

k =

2