6. Top K Frequent Words

Given a non-empty list of words, return the k most frequent elements.

Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.

Example 1:
Input: ["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: ["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.

Solution: (Using Array sorting)

class Solution
{
public:
    static bool comparator(const pair<string, int> &a, const pair<string, int> &b)
    {
        if (a.second == b.second)
        {
            return a.first < b.first;
        }
        else
        {
            return a.second > b.second;
        }
    }

    vector<string> topKFrequent(vector<string> &words, int k)
    {
        map<string, int> m;
        vector<pair<string, int>> v;
        vector<string> res;

        for (int i = 0; i < words.size(); i++)
        {
            m[words[i]]++;
        }

        for (auto itr = m.begin(); itr != m.end(); itr++)
        {
            v.push_back({itr->first, itr->second});
        }

        sort(v.begin(), v.end(), comparator);

        for (int i = 0; i < k; i++)
        {

            res.push_back(v[i].first);
        }

        return res;
    }
};

Time Complexity: O(n log n + n)

Solution: (Using Priority Queue)

class Solution
{
public:
    struct compare
    {

        bool operator()(const pair<string, int> &a, const pair<string, int> &b)
        {
            if (a.second == b.second)
            {
                return a.first > b.first;
            }

            return a.second < b.second;
        }
    };

    vector<string> topKFrequent(vector<string> &words, int k)
    {

        unordered_map<string, int> m;
        priority_queue<pair<string, int>, vector<pair<string, int>>, compare> pq;
        vector<string> res;

        for (int i = 0; i < words.size(); i++)
        {
            m[words[i]]++;
        }

        for (auto itr = m.begin(); itr != m.end(); itr++)
        {
            pq.push({itr->first, itr->second});
        }

        for (int i = 1; i <= k; i++)
        {
            res.push_back(pq.top().first);
            pq.pop();
        }

        return res;
    }
};

Time Complexity: O(n log k + n)

Last updated