Top K Frequent Words - Complete Solution Guide
Top K Frequent Words is LeetCode problem 692, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
Given an array of strings words and an integer k , return the k most frequent strings . Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order . 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. Note that "i" comes before "love" due to a lower alphabetical order. Example 2: Input: words = ["the","day","is","s
Detailed Explanation
The problem requires you to find the `k` most frequent words from a given list of words. The output should be a list of these `k` words, sorted first by frequency in descending order (most frequent first) and then, for words with the same frequency, by lexicographical order (alphabetical order). The input consists of a list of strings `words` and an integer `k`, representing the number of most frequent words to return. Constraints include the length of the `words` array (1 to 500), the length of each word (1 to 10), and the range of `k` (1 to the number of unique words).
Solution Approach
The solution uses a combination of a hash map and a min-heap. First, it counts the frequency of each word using a hash map. Then, it iterates through the hash map, pushing each word-frequency pair onto the min-heap. The min-heap is structured to maintain the `k` most frequent words. If the heap size exceeds `k`, the least frequent word (according to the defined comparison logic) is removed from the heap. Finally, the words are extracted from the min-heap and arranged in the correct order (descending frequency, then lexicographical order) to generate the final result.
Step-by-Step Algorithm
- Step 1: Create a hash map (or Counter) to store the frequency of each word in the input `words` list.
- Step 2: Iterate through the `words` list, updating the frequency count in the hash map for each word.
- Step 3: Create a min-heap (priority queue) of size `k`. The heap will store word-frequency pairs.
- Step 4: Define a custom comparator for the min-heap. The comparator should prioritize words with lower frequencies and, for words with equal frequencies, prioritize words with higher lexicographical order.
- Step 5: Iterate through the hash map, adding each word-frequency pair to the min-heap. If the heap size exceeds `k`, remove the element at the root (the smallest element).
- Step 6: Once all words have been processed, extract the elements from the min-heap in reverse order (because it's a min-heap) and add their words to the result list. The order within the heap guarantees that the results are sorted according to the problem's requirements.
- Step 7: Return the result list.
Key Insights
- Insight 1: Counting the frequency of each word is essential for determining the most frequent ones. A hash map (or Counter in Python) is suitable for efficiently storing word counts.
- Insight 2: A min-heap (priority queue) can be used to keep track of the `k` most frequent words seen so far. By maintaining a heap of size `k`, we ensure that only the top `k` frequent words are retained, leading to an O(n log k) time complexity.
- Insight 3: The comparison logic within the min-heap is crucial. We need to compare words based on frequency first (lower frequency is smaller) and then lexicographically (higher alphabetical order is smaller) for words with the same frequency, to satisfy the sorting requirements.
Complexity Analysis
Time Complexity: O(nlogk)
Space Complexity: O(n)
Topics
This problem involves: Array, Hash Table, String, Trie, Sorting, Heap (Priority Queue), Bucket Sort, Counting.
Companies
Asked at: Attentive, Box, Intel, Netflix, Palo Alto Networks, Pocket Gems, Robinhood, ServiceNow, Smartsheet, Yandex, Yelp.