Problem · Array
Stable Top K Frequent Words
Learn this problemProblem statement
Given an array of words and an integer k, return the k distinct words with the highest frequencies.
Rank words by descending frequency. When two words have the same frequency, rank the word whose first occurrence has the smaller array index first. Return the selected words in this ranking order.
Function
topKFrequentStable(words: String[], k: int) → String[]Examples
Example 1
words = ["apple","banana","apple","cherry","banana","date"]k = 2return = ["apple","banana"]apple and banana each occur twice. The first apple appears at index 0, before the first banana at index 1.
Example 2
words = ["z","a","z","a","b"]k = 3return = ["z","a","b"]z and a have frequency two and keep first-occurrence order. The remaining word b is third.
Example 3
words = ["solo"]k = 1return = ["solo"]The only distinct word is selected.
Constraints
1 <= words.length <= 2000001 <= words[i].length <= 30- Each word contains lowercase English letters.
1 <= k <=the number of distinct words.