Top K Frequent Elements LeetCode Solution

Last updated on October 5th, 2024 at 08:54 pm

Here, We see Top K Frequent Elements LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Topics

Hash Table, Heap

Companies

Pocketgems, Yelp

Level of Question

Medium

Top K Frequent Elements LeetCode Solution

Top K Frequent Elements LeetCode Solution

Problem Statement

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2:
Input: nums = [1], k = 1
Output: [1]

1. Top K Frequent Elements Leetcode Solution C++

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int,int> map;
        for(int num : nums){
            map[num]++;
        }
        vector<int> res;
        priority_queue<pair<int,int>> pq; 
        for(auto it = map.begin(); it != map.end(); it++){
            pq.push(make_pair(it->second, it->first));
            if(pq.size() > (int)map.size() - k){
                res.push_back(pq.top().second);
                pq.pop();
            }
        }
        return res;
    }
};

2. Top K Frequent Elements Leetcode Solution Java

class Solution {
    public int[] topKFrequent(int[] nums, int k) {
	    List<Integer>[] freqSorted = new List[nums.length +1];
	    Map<Integer, Integer> frequencyMap = new HashMap();
	    List<Integer> res = new ArrayList();
	    for(int n: nums)
		    frequencyMap.put(n, frequencyMap.getOrDefault(n, 0) + 1);
        for(int key: frequencyMap.keySet()){
	        if(freqSorted[frequencyMap.get(key)] == null)
		        freqSorted[frequencyMap.get(key)] = new ArrayList();
	        freqSorted[frequencyMap.get(key)].add(key);
        }
        for(int i = freqSorted.length - 1; i >= 0 && res.size() < k; i--)
	        if(freqSorted[i] != null){
			    res.addAll(freqSorted[i]);
        }
    return res.stream().mapToInt(i->i).toArray();
    }
}

3. Top K Frequent Elements Solution JavaScript

var topKFrequent = function(nums, k) {
    const freqMap = new Map();
    const bucket = [];
    const result = [];
    for(let num of nums) {
        freqMap.set(num, (freqMap.get(num) || 0) + 1);
    }
    for(let [num, freq] of freqMap) {
        bucket[freq] = (bucket[freq] || new Set()).add(num);
    }
    for(let i = bucket.length-1; i >= 0; i--) {
        if(bucket[i]) result.push(...bucket[i]);
        if(result.length === k) break;
    }
    return result;
};

4. Top K Frequent Elements Solution Python

class Solution(object):
    def topKFrequent(self, nums, k):
        map=Counter(nums)
        result=[]
        for key,value in map.items():
            result.append([key,value])
        result.sort(key=lambda x:x[1],reverse=True)
        return [x[0] for x in result[:k]]
Scroll to Top