692. Top K Frequent Words

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.

Constraints:

  • 1 <= words.length <= 500

  • 1 <= words[i].length <= 10

  • words[i] consists of lowercase English letters.

  • k is in the range [1, The number of unique words[i]]

Follow-up: Could you solve it in O(n log(k)) time and O(n) extra space?

Intuition

Approach:
Custom Comparator

https://leetcode.com/problems/top-k-frequent-words/description/

Approach 1:

C++
typedef pair<int, string> pis;

struct Comp {
    bool operator()(const pair<int, string>& p1, const pair<int, string>& p2) {
        // Compare integers in descending order
        if (p1.first != p2.first) {
            return p1.first < p2.first; // Change to > for ascending order
        }
        // If integers are equal, compare strings in ascending order
        return p1.second > p2.second; // Change to < for descending order
    }
};

class Solution {
public:
    vector<string> topKFrequent(vector<string>& arr, int k) {
        vector<string> ans;
        unordered_map<string, int> mp;
        priority_queue<pis, vector<pis>, Comp> pq;
        for(auto &it: arr)
            mp[it]++;

        for(auto &it: mp)
            pq.push({it.second, it.first});

        while(k--){
            ans.push_back(pq.top().second);
            pq.pop();
        }

        return ans;
    }
};

Approach 2:

C++

Approach 3:

C++

Approach 4:

C++

Similar Problems

Last updated