FastPrepStable Top K Frequent Words
Problem · Array

Stable Top K Frequent Words

Learn this problem
MediumGoogle logoGoogleFULLTIMEPHONE SCREEN
See Google hiring insights

Problem 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 <= 200000
  • 1 <= words[i].length <= 30
  • Each word contains lowercase English letters.
  • 1 <= k <= the number of distinct words.

More Google problems

drafts saved locally
public String[] topKFrequentStable(String[] words, int k) {
    // Write your code here.
}
words["apple","banana","apple","cherry","banana","date"]
k2
expected["apple", "banana"]
checking account