Top K Frequent Words

Medium · Heap & Counting · Array · Hash Table · String · Trie · Sorting · Heap (Priority Queue) · Bucket Sort · Counting

Problem

Given a list of words and an integer k, return the k most frequent words, ranked from the most frequent to the least.

Words with the same frequency are ranked alphabetically, in dictionary order, so "a" comes before "ab" and "ab" before "b". The order of the returned list is part of the answer.

Examples

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

"i" and "love" both appear twice, more than any other word. They tie, so they are ranked alphabetically: "i" before "love".

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

"the" appears 4 times, "is" 3 times, "sunny" twice and "day" once.

Constraints

Approaches

Follow-up

Could you do it in O(n log k) time and O(n) extra space?

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…