← Home

692. Top K Frequent Words

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
heap / priority queueC++Markdown
692

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 692. Top K Frequent Words, the solution in this repository is mainly a heap / priority queue solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: heap / priority queue.

The notes already sitting in the source point us in the right direction:

  • Heap
  • time: O(Nlogk), push N times, each O(logk), space: O(N), space taken by map

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are topKFrequent.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • The queue gives the solution a level-by-level or frontier-style traversal.
  • The heap keeps the best candidate available without sorting the whole world every time.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(Nlogk), push N times, each O(logk), space: O(N), space taken by map
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Heap
02//Runtime: 24 ms, faster than 13.26% of C++ online submissions for Top K Frequent Words.
03//Memory Usage: 9.1 MB, less than 100.00% of C++ online submissions for Top K Frequent Words.
04//time: O(Nlogk), push N times, each O(logk), space: O(N), space taken by map
05class Solution {
06public:
07    vector<string> topKFrequent(vector<string>& words, int k) {
08        //use unordered_map rather than map to speed up
09        unordered_map<string, int> counter;
10        
11        auto comp = [&counter](const string& lhs, const string& rhs){
12            /*if we want an element to be popped from priority queue earlier,
13            then we need to make it rank lower in the sorted array
14            */
15            // cout << lhs << " " << counter[lhs] << " " << rhs << " " << counter[rhs] << endl;
16            // cout << lhs << " " << rhs << " " << (lhs > rhs) << endl;
17            return (counter[lhs] == counter[rhs]) ? (lhs > rhs) : 
18                (counter[lhs] < counter[rhs]);
19        };
20        
21        priority_queue<string , vector<string>, decltype(comp)> pq(comp);
22        vector<string> ans;
23        
24        for(string& word : words){
25            counter[word]++;
26        }
27        
28        /*
29        only when we have looked through words, 
30        counter has correct count of each word's occurrence
31        */
32        for(auto it = counter.begin(); it != counter.end(); it++){
33            pq.push(it->first);
34        }
35        
36        while(k-- > 0){
37            ans.push_back(pq.top());
38            pq.pop();
39        }
40        
41        return ans;
42    }
43};

Cost

Complexity

Time
O(Nlogk), push N times, each O(logk), space: O(N), space taken by map
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.