692. Top K Frequent Words
LeetCode 692. Top K Frequent Words
Description
Given a non-empty list of words, return the k most frequent elements.
Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.
Example 1:
Example 2:
Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Input words contain only lowercase letters.
Follow up:
Try to solve it in O ( n log k ) time and O ( n ) extra space.
Tags
Hash Table, Heap, Trie
Solution
For other solutions see Reference section.
The first step is build a hash table who maps a word to its frequency. Then we invert this mapping with a 2D string slice, called freq2word
. Its index is word frequency, and the element corresponding to each index in freq2word
is an alphabetical-ordered string array, whose elements share the same frequency index
. To keep each element of freq2word
is sorted, we apply a binary search function to insert each incoming element instead of appending.
After building freq2word
, we iterate over it from right. If the length of the current element, which is a slice, is smaller than the result array's remaining capacity, we append all of them to the result. Otherwise, we append words of the current element to the result one by one until the length of the result array is k
.
Complexity
Time complexity: ,
m
is the number of unique words;Space complexity: , actually
freq2word
storesn
words.
Code
Reference
Last updated
Was this helpful?