692. Top K Frequent Words

T: O(nlogk)

S: O(n)

```java
class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        int n = words.length;
        Map<String, Integer> freq = new HashMap<>();
        for (String w : words) {
            freq.put(w, freq.getOrDefault(w, 0)+1);
        }

        // small count pop first, and lexicographical order larger pop first, so that's why b.compareTo(a)
        Queue<String> pq = new PriorityQueue<>((a, b) -> freq.get(a).equals(freq.get(b)) ? b.compareTo(a) : freq.get(a) - freq.get(b));
        for (String key :freq.keySet()) {
            pq.offer(key);
            if (pq.size() > k) {
                pq.poll();
            }
        }
        List<String> result = new ArrayList<>();
        while (!pq.isEmpty()) {
            result.add(pq.poll());
        }
        Collections.reverse(result);
        return result;
    }
    
}
/**
bucket + list

seems still nlognc
T: O(n*)

 */
```

Trie + bucket

this question, because it ask, if freq count are the same, return list by lexico order smaller, that's why need Trie

if don't care this, we can only use bucket and list to give ans (like 347 bucket solution)

T: O(n)

S: O(n)

Last updated

Was this helpful?