Top K Frequent Words

Given a list of words and an integer k, return the k most frequent words. Order the result by decreasing frequency, and for equal frequency use lexicographically smaller words first.

Input Format

words = array of words, k = number of results

Output Format

k most frequent words sorted by frequency desc and lexicographic asc on ties

Constraints

  • 1 <= words.length <= 10^5
  • 1 <= words[i].length <= 10^3
  • 1 <= k <= number of unique words

Examples

Example 1:

Input:

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

Output:

["i","love"]

Explanation:

i and love are the two most frequent words.

Example 2:

Input:

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

Output:

["the","is","sunny","day"]

Explanation:

Frequencies are 4, 3, 2, and 1 respectively.

Loading...
Top K Frequent Words - Heap DSA Problem