Saturday, April 23, 2022

Leet Code 692. Top K Frequent Words



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.



package pep.Day66;

import java.util.*;

public class LeetCode_692_Top_k_Frequent_Words {
public static void main(String[] args) {
int k = 2;
System.out.println(topKFrequent(new String[]{"i", "love", "leetcode", "i",
        "love", "coding"}, k));
}

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

PriorityQueue<String> pq = new PriorityQueue<>(new Comparator<String>() {
@Override
public int compare(String child, String parent) {
int frequency1 = hashMap.get(child);
int frequency2 = hashMap.get(parent);

// when count will be same then, use alphabetical order descending
if (frequency1 == frequency2)
return parent.compareTo(child);
//return newVal - oldVal;
return frequency1 - frequency2;
}
});

for (String s : hashMap.keySet()) {
pq.add(s);
if (pq.size() > k)
pq.remove();
}

List<String> ans = new LinkedList<>();

while (!pq.isEmpty())
// this will add the value to 0th index and
// then shift previous and add next on 0th index only
ans.add(0, pq.remove());

return ans;
}

}

No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...