Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Top K Frequent Words

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

i’m trying to solve this problem using Frequencies and store the most ones and loop k times to get all of them but i have a problem i can’t return them as a lexicographical order
upd : i solved it thanks !

class Solution {
public:
    vector<string> topKFrequent(vector<string>& words, int k) {
         int n =words.size();
        map<string ,int > Freq;
      
        for (int i = 0 ; i< n;i++)
            Freq[words[i]]++;
        
        vector<pair<string ,int >>result;
        vector<string>ans;
        for (auto it : Freq)
            result.push_back({it.first,it.second});
        sort(result.begin(),result.end());
        for (int i = 0 ; i < min(k,n);i++)
            ans.push_back(result[i].first);
        return ans;
    }
};

>Solution :

you have to use compare function as a third parameter in the sort function.
compare function will sort the values as you want exactly!

class Solution {
public:
static bool cmp(pair<string ,int > &p1 ,  pair<string ,int > &p2)
    {
        if (p1.second == p2.second)return p1.first < p2.first ;
            return p1.second > p2.second;
    } 
    vector<string> topKFrequent(vector<string>& words, int k) {
         int n =words.size();
        map<string ,int > Freq;

        for (int i = 0 ; i< n;i++)
            Freq[words[i]]++;

        vector<pair<string ,int >>result;
        vector<string>ans;
        for (auto &it : Freq)
            result.push_back({it.first,it.second});
        sort(result.begin(),result.end(),cmp);
        for (int i = 0 ; i < min(k,n);i++)
            ans.push_back(result[i].first);
        return ans;
    }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading