Top K Frequent Words
Explanation & Solution
Description
Given an array of strings words and an integer k, return the k most frequent strings.
Return the answer sorted by frequency from highest to lowest. If two words have the same frequency, sort them in alphabetical order.
Examples
Explanation: "i" and "love" are the two most frequent words. "i" appears 2 times and "love" appears 2 times. "i" comes before "love" alphabetically.
Explanation: "the" appears 4 times, "is" 3 times, "sunny" 2 times, and "day" 1 time. They are sorted by frequency, with ties broken alphabetically.
Explanation: All words appear once, so they are sorted alphabetically.
Constraints
1 <= words.length <= 5001 <= words[i].length <= 10words[i]consists of lowercase English letters.kis in the range[1, number of unique words].- The answer is guaranteed to be unique.
Approach
Top K Elements pattern
1. Build a Frequency Map
- Iterate through the
wordsarray. - Use a hash map to count the frequency of each word.
- For example,
["i","love","i"]produces{ "i": 2, "love": 1 }.
2. Extract Unique Words
- Get all unique words from the hash map's keys.
- These are the candidates we need to rank.
3. Sort by Frequency and Alphabetical Order
- Sort the unique words using a custom comparator:
- Primary sort: by frequency in descending order (higher frequency first).
- Secondary sort: by alphabetical order (for words with equal frequency).
- This ensures ties are broken correctly.
4. Return the Top K Words
- Slice the first
kelements from the sorted array. - These are the k most frequent words in the required order.
Key Insight
The core idea is to combine a hash map for counting with a custom sort that handles both frequency and lexicographic ordering. Sorting all unique words takes O(n log n) time where n is the number of unique words, and building the frequency map takes O(m) where m is the total number of words. Overall time complexity: O(m + n log n) and space complexity: O(n) for the hash map and sorted array.