FastPrepTop K Frequent Words

Top K Frequent Words

Bloomberg LP logoBloomberg LP● MediumNEW GRADONSITE INTERVIEW
Learn

Problem statement

Given an array words and integer k, return the k most frequent distinct words.

Rank words by descending frequency. If two words have the same frequency, the lexicographically smaller word ranks first.

Function

topKFrequentWords(words: String[], k: int) → String[]

Examples

Example 1

words = ["i","love","leetcode","i","love","coding"]k = 2return = ["i","love"]

Both occur twice, and i is lexicographically smaller.

Example 2

words = ["the","day","is","sunny","the","the","the","sunny","is","is"]k = 4return = ["the","is","sunny","day"]

Frequencies are 4, 3, 2, and 1.

Constraints

  • 1 <= words.length <= 10^5.
  • 1 <= k <= number of distinct words.
  • Words are nonempty lowercase English strings.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public String[] topKFrequentWords(String[] words, int k) {
  // Write your code here.
}
words["i","love","leetcode","i","love","coding"]
k2
expected["i", "love"]
Checking account…