692. Top K Frequent Words

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.

My Solutions:

public List<String> topKFrequent(String[] words, int k) {
    HashMap<String, Integer> map = new HashMap<>();
    for (String word : words) map.put(word, map.getOrDefault(word, 0) + 1);

    // a pq with bigger number first, and order alphabetically
    PriorityQueue<Map.Entry<String, Integer>> pq = new PriorityQueue<> (
        new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> a, Map.Entry<String, Integer> b) {
                if (a.getValue() != b.getValue()) return b.getValue() - a.getValue();
                return a.getKey().compareTo(b.getKey());
            }
        }
    );

    // add elements to pq
    for (Map.Entry<String, Integer> element : map.entrySet()) pq.add(element);

    List<String> res = new ArrayList<>();
    for (int i = 0; i < k; i++) res.add(pq.poll().getKey());
    return res;
}

Last updated