March 01, 2022

692. Top K Frequent Words

Originally published at 2019-09-26

692. Top K Frequent Words

Time Complexity = O(nlogk) Space Complecity = O(k)

class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        List<String> res = new ArrayList<>();
        
        Map<String, Integer> freqMap = new HashMap<>();
        for (String word : words) {
            freqMap.put(word, freqMap.getOrDefault(word, 0) + 1);
        }
        PriorityQueue<Map.Entry<String, Integer>> minHeap = 
            new PriorityQueue<>((a, b) -> 
                                a.getValue() == b.getValue()? 
                                b.getKey().compareTo(a.getKey()) : 
                                a.getValue() - b.getValue());
        for (Map.Entry<String, Integer> entry : freqMap.entrySet()) {
            minHeap.offer(entry);
            if (minHeap.size() > k) {
                minHeap.poll();
            }
        }
        while (!minHeap.isEmpty()) {
            res.add(0, minHeap.poll().getKey());
        }
        return res;
    }
}
comments powered by Disqus