Heap Custom Sort comparator

Learnings

    auto compare = [](const PII &a, const PII &b){
        return a.second < b.second;
    };
    priority_queue<PII, vector<PII>, decltype(compare)> pq(compare);
    
    
    or
priority_queue<pis, vector<pis>, Comp> pq;
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
    }
};

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

Intuition

https://leetcode.com/problems/top-k-frequent-words/solutions/1274279/cpp-c-priority-queue-custom-comparator-and-solution-explain-o-nlogk-solution/

https://leetcode.com/problems/minimum-array-length-after-pair-removals/description/ https://www.youtube.com/watch?v=Qt_gbCWqFdY&ab_channel=AryanMittal https://leetcode.com/problems/top-k-frequent-words/description/

Last updated