Top K Frequent Words LeetCode Solution

Here, We see Top K Frequent Words 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

Top K Frequent Words LeetCode Solution

Top K Frequent Words LeetCode Solution

Problem Statement

Given an array of strings words and an integer k, return the k most frequent strings.

Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order.

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.

Example 2:
Input: words = [“the”,”day”,”is”,”sunny”,”the”,”the”,”the”,”sunny”,”is”,”is”], k = 4
Output: [“the”,”is”,”sunny”,”day”]
Explanation: “the”, “is”, “sunny” and “day” are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.

Top K Frequent Words LeetCode Solution C++

class Solution {
public:
    static bool comparator(pair<string,int> p1, pair<string,int> p2)
    {
        if(p1.second>p2.second || (p1.second==p2.second && p1.first<p2.first))
            return true;
        return false;
    }
    
    vector<string> topKFrequent(vector<string>& words, int k) {
        unordered_map<string,int> m1;
        for(int i=0; i<words.size(); i++)
            m1[words[i]]++;
        vector<pair<string,int>> v1;
        for(auto it=m1.begin(); it!=m1.end(); it++)
            v1.push_back({it->first,it->second});
        sort(v1.begin(),v1.end(),comparator);
        vector<string> ans;
        for(int i=0; i<k; i++)
        {
            ans.push_back(v1[i].first);
        }
        return ans;
    }
};Code language: PHP (php)

Top K Frequent Words LeetCode Solution Java

class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        HashMap<String,Integer> freq=new HashMap<>();
        for(int i=0;i<words.length;i++)
        {
            freq.put(words[i],freq.getOrDefault(words[i],0)+1);
        }
        List<String> res = new ArrayList(freq.keySet());
        Collections.sort(res, (w1, w2) -> freq.get(w1).equals(freq.get(w2)) ?
                w1.compareTo(w2) : freq.get(w2) - freq.get(w1));
        return res.subList(0, k);
    }
}Code language: JavaScript (javascript)

Top K Frequent Words Solution JavaScript

var topKFrequent = function(words, k) {
    let hash = {};
    for (let word of words) {
        hash[word] = hash[word]+1||1;
    }
    let result = Object.keys(hash).sort((a,b)=>{
            let countCompare = hash[b] - hash[a];
            if (countCompare == 0) return a.localeCompare(b);
            else return countCompare;
        }   
    );
    return result.slice(0, k);    
};Code language: JavaScript (javascript)

Top K Frequent Words Solution Python

class Solution(object):
    def topKFrequent(self, words, k):
        dict = {}
        for x in words:
            if x in dict:
                dict[x] += 1
            else:
                dict[x] = 1
        res = sorted(dict, key=lambda x: (-dict[x], x))
        return res[:k]
Scroll to Top