> For the complete documentation index, see [llms.txt](https://emmaguo100.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://emmaguo100.gitbook.io/leetcode/02-10-2022-692.md).

# 02/10/2022 692

692\. Top K Frequent Words

our desired result is to grab the higher frequency and smaller alphabet, we want to locate things in the opposite way in min-heap; **lower frequency** and **bigger alphabet**, so that we could *remove an undesired candidate each time*.&#x20;

```
// Some code

class Solution {
    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);
        }   
        //noted that b.compareTo(a)
        Queue<String> minHeap = new PriorityQueue<>((a,b) -> 
            map.get(a) == map.get(b) ? b.compareTo(a) : map.get(a)-map.get(b));
        for(String key: map.keySet()){
            minHeap.add(key);
            if(minHeap.size() > k){
                minHeap.poll();
            }
        }
        List<String> result = new ArrayList<>();
        while(!minHeap.isEmpty()){
            result.add(0, minHeap.poll());
        }
        
        return result;
    }
}
```

```
    return result;
}
```

}
