692 Top K Frequent Words
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. Can you solve it in O(n) time with only O(k) extra space?
The Idea: Python makes this really easy. First accumulate the frequencies and then sort by value descending, and then secondarily by key in ascending. Finally return the slice of the first k values from the sorted list of tuples.
Complexity: O(N + NlogN + k) time and O(N) space
Last updated