Formatted question description: https://leetcode.ca/all/692.html

692. Top K Frequent Words

Level

Medium

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:

Input: [“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: [“the”, “day”, “is”, “sunny”, “the”, “the”, “the”, “sunny”, “is”, “is”], k = 4

Output: [“the”, “is”, “sunny”, “day”]

Explanation: “the”, “is”, “sunny” and “day” are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.

Note:

  1. You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  2. Input words contain only lowercase letters.

Follow up:

  1. Try to solve it in O(n log k) time and O(n) extra space.

Solution

First loop over words and obtain each word’s number of occurrences. Use a map to store each word and its number of occurrences. Then use a priority queue to store each word and its number of occurrences, where the word with lowest number of occurrences or the highest alphabetical order is polled first. For each entry of the map, create an object from the entry and offer it into the priority queue. If the priority queue’s size is greater than k, then poll one element from the priority queue. This can make sure that there are at most k elements in the priority queue and the elements are the most frequent.

After all the words are checked, use a list to store all the words in the priority queue (in the order that they are polled from the priority queue). Then reverse the list and return.

public class Top_K_Frequent_Words {

    public static void main(String[] args) {
        Top_K_Frequent_Words out = new Top_K_Frequent_Words();
        Solution s = out.new Solution();

        System.out.println(s.topKFrequent(new String[]{"the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"}, 4));
        System.out.println(s.topKFrequent(new String[]{"i", "love", "leetcode", "i", "love", "coding"}, 2));
    }

    // ref: https://leetcode.com/articles/top-k-frequent-words/
    // using a heap (PQ)
    // Time Complexity: O(Nlogk), where N is the length of words.
    //          We count the frequency of each word in O(N) time, then we add N words to the heap, each in O(logk) time.
    //          Finally, we pop from the heap up to k times. As k≤N, this is O(Nlogk) in total.
    // Space Complexity: O(N), the space used to store our count.
    class Solution {
        public List<String> topKFrequent(String[] words, int k) {
            Map<String, Integer> count = new HashMap<>();
            for (String word: words) {
                count.put(word, count.getOrDefault(word, 0) + 1);
            }
            PriorityQueue<String> heap = new PriorityQueue<String>(
                (w1, w2) -> count.get(w1).equals(count.get(w2)) ?
                    w2.compareTo(w1) : count.get(w1) - count.get(w2)
            );

            for (String word: count.keySet()) {
                heap.offer(word);
                if (heap.size() > k) heap.poll();
            }

            List<String> result = new ArrayList<>();
            while (!heap.isEmpty()) result.add(heap.poll());
            Collections.reverse(result);

            return result;

//            // below also working
//            List<String> result = new ArrayList<>();
//            for (int i = k - 1; i >= 0; i--) {
//                result.add(0, heap.poll());
//            }
//
//            return result;
        }
    }

}

All Problems

All Solutions