Top K Frequent Words

Medium Heap Sorting

Problem

Return the k most frequent words in a list. If two words have the same frequency, the lexicographically smaller word comes first. The answer should be ordered by frequency descending, then by the lexical rule.

Original: LeetCode 692: Top K Frequent Words.

Examples

Example 1

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

Both appear twice; "i" comes first alphabetically.

Example 2

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

Constraints

  • 1 <= words.length <= 500
  • 1 <= words[i].length <= 10
  • words[i] consists of lowercase English letters.
  • k is in the range [1, The number of unique words[i]]

Hints

Solution

Tried it yourself? The approach, complexity, and code stay hidden until you choose.

Sources (2)
  1. LeetCode 692: Top K Frequent Wordsleetcode.com
  2. Java SE 17 API: PriorityQueuedocs.oracle.com