DEV Community

Yoges
Yoges

Posted on

Top K Frequent Elements

Today i try to solve Top K Frequent Elements the problem is simple you need to return the k most frequent elements.

Problem:

Given an integer array nums and an integer k, return the k most frequent elements within the array.

The test cases are generated such that the answer is always unique.

You may return the output in any order.

Solution:

I choose HashMap to track the frequency of the element

Then we need to take the largest k elements
this is the tricky part

How can i get the largest value(count of the element) from the map and store the exact k largest values??

Then i endup with Min Heap. But the challenge is store the key, value pairs in Priority Queue.
For that i use map.entry to store in Priority Queue it compares the values in the map. It's sounds confusing but it too easy..

JAVA code:

class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>();
        //we have to return most frequent elements.Elements count should be k
        //ex: k=2 you have to return 2 element. that element should be have most frequency

        //step 1: store the element with frequency as a key, value pair in map
        for(int num : nums){
            map.put(num, map.getOrDefault(num, 0)+1);
        }

        //Use MinHeap to get the most frequent value
        // the will be store k elements if the size of pq > k we need remove smallest element so just use poll method to remove it.

        PriorityQueue<Map.Entry<Integer, Integer>> pq =
                    new PriorityQueue<>(
                        Comparator.comparingInt(Map.Entry::getValue) // pq compare the value here we are storing the map entry so we need to mentain which value should be compared here
                        //Here we need compare the values inorder to get the highest frequency
                    );

         for(Map.Entry<Integer, Integer> entry : map.entrySet()){
            pq.offer(entry);
            if(pq.size() > k){
                pq.poll();
            }
         }
         int[] ans = new int[k];
         int i = 0;
        // Then finally store it in array return it
         while(!pq.isEmpty()){
             Map.Entry<Integer, Integer> entry = pq.poll();
             ans[i++] = entry.getKey();
         }
         return ans;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)